Python 中字符串中的第一个唯一字符

pythonserver side programmingprogramming更新于 2025/10/31 10:52:17

假设我们有一个字符串,我们必须找到字符串中的第一个唯一字符。因此,如果字符串类似于"people",则出现次数为 1 的第一个字母是"o"。因此将返回索引,即此处的 2。如果没有这样的字符,则返回 -1。

为了解决这个问题,我们将遵循以下步骤 −

  • 创建一个频率图
  • 对于字符串中的每个字符 c,执行
    • 如果 c 不在频率中,则将其插入频率中,并将值设为 1
    • 否则,增加频率中的计数
  • 扫描频率图,如果特定键的值为 1,则返回该键,否则返回 -1

示例

让我们看下面的实现,以便更好地理解 −

class Solution(object):
   def firstUniqChar(self, s):
      """
      :type s: str
      :rtype: int
      """
      frequency = {}
      for i in s:
         if i not in frequency:
            frequency[i] = 1
         else:
            frequency[i] +=1
      for i in range(len(s)):
         if frequency[s[i]] == 1:
            return i
      return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))

输入

"people"
"abaabba"

输出

2
-1

相关文章


有用资源