5/27 每日一題(返回唯一值的索引)
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 1:
Input: s = "leetcode" Output: 0
Example 2:
Input: s = "loveleetcode" Output: 2
Example 3:
Input: s = "aabb" Output: -1
Constraints:
1 <= s.length <= 105sconsists of only lowercase English letters.
class Solution:
def firstUniqChar(self, s: str) -> int:
s_c=Counter(s) #建立一個key=字元,value=出現次數的字典
for i,j in s_c.items():
if j==1: #如果有唯一值,返回該元素的索引值
return s.index(i)
return -1 #迴圈結束表示不存在唯一值
-----------------參考解答1.計算第一次出現並打破循環
class Solution: def firstUniqChar(self, s: str) -> int: for i,c in enumerate(s): if s.count(c)==1: return i break return -1 #please upvote me it would encourage me alot2. 使用哈希表和集合
class Solution: def firstUniqChar(self, s: str) -> int: dic={} seen=set() for ind,let in enumerate(s): if let not in seen: dic[let]=ind seen.add(let) elif let in dic: del dic[let] return min(dic.values()) if dic else -1 //please upvote me it would encourage me alot
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁