387. First Unique Character in a String

题目

Given a string s, return 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 <= 105
  • s consists of only lowercase English letters.

解题

有几种思路,

1.遍历2遍,时间复杂度O(n)。

public class Solution {
    public int firstUniqChar(String s) {
        int freq [] = new int[26];
        for(int i = 0; i < s.length(); i ++)
            freq [s.charAt(i) - 'a'] ++;
        for(int i = 0; i < s.length(); i ++)
            if(freq [s.charAt(i) - 'a'] == 1)
                return i;
        return -1;
    }
}

2.遍历1遍,时间复杂度O(n) 

def firstUniqChar(s: str) -> int:
    if len(s) < 1:
        return -1
    dict = {}
    num=0
    for i in s:
        if(i in dict.keys()):
            dict[i]=float("inf")
        else:
            dict[i]=num
        num=num+1
    minValue = min(dict.values())
    return minValue if minValue < float("inf") else -1
print(firstUniqChar('aadadaad'))

3.这个方法从算法上来说,是O(n)。评论区大神指出,这个方法之所以快,是因为index函数是调用的C函数,因此执行快。所以这个方法让我们学到了C语言真的很快,python代码可以通过调用C函数的方式来提高执行速度,算是个小技巧。

  def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        letters='abcdefghijklmnopqrstuvwxyz'
        index=[s.index(l) for l in letters if s.count(l) == 1]
        return min(index) if len(index) > 0 else -1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值