FirstNotRepeatingCharacter
5102 ワード
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example
For s = "abacabad", the output should be
solution(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
For s = "abacabaabacaba", the output should be
solution(s) = '_'.
There are no characters in this string that do not repeat.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string s
A string that contains only lowercase English letters.
Guaranteed constraints:
1 ≤ s.length ≤ 105.
[output] char
The first non-repeating character in s, or '_' if there are no characters that do not repeat.
文字列:
これは重複しないインデックスが最も速いアルファベットを解く問題です.
最初の私の考えは:
dictでX:1のみを選択し、再度複文で最小値を見つけます.
値が1の場合はcharを返し、ない場合は「」を返します.
コード:
def solution(s):
mydict = {}
min_value = 100000
for char in s :
if mydict.get(char) == None :
mydict[char] = 1
else :
mydict[char] += 1
for key in mydict :
if mydict[key] == 1 :
if s.index(key) < min_value :
min_value = s.index(key)
if min_value == 100000 :
return "_"
else :
return s[min_value]
時間内にうまく解決した.回答:
def solution(s):
for c in s:
if s.index(c) == s.rindex(c):
return c
return '_'
rindex()またはrfind()を用いて解く正解が上位にランクされている.rindex(),rfind()は,末尾からインデックスを返す方法である.
ただし、rindex()に対応する要素がない場合、error、rfind()は-1を返します.
実は、私はこの方法を知らない.
rindex()とrfind()について理解した.
問題を解くとき、私は私の不足点を知っていて、もっと知りたいです.最も重要なのは堅持することだ.
Reference
この問題について(FirstNotRepeatingCharacter), 我々は、より多くの情報をここで見つけました https://velog.io/@1984/FirstNotRepeatingCharacterテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol