1、字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
代码如下:通过68ms,
class Solution: def firstUniqChar(self, s): """ :type s: str :rtype: int """ #### ref = "abcdefghijklmnopqrstuvwxyz" index_list = [] for i in ref: if(s.count(i) == 1): index_list.append(s.index(i)) if len(index_list) > 0: return min(index_list) else: return -1
2、 有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram" 输出: true
示例 2:
输入: s = "rat", t = "car" 输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
代码如下:通过52ms
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ import collections dict_s = collections.Counter(s) dict_t = collections.Counter(t) if len(dict_s) != len(dict_t): return False for key, value in dict_s.items(): if key in dict_t and value == dict_t[key]: continue else: return False return True