77、字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = “leetcode”
返回 0.

s = “loveleetcode”,
返回 2.

跟上一题基本一样

class Solution {
    public int firstUniqChar(String s) {
        int flag[]= new int[123];
		
		for (int i = 0; i < s.length(); i++) {
			char tem = s.charAt(i);
			flag[tem] ++;
		}
		for (int i = 0; i < s.length(); i++) {
			char tem = s.charAt(i);
			if(flag[tem]==1) 
				return i;
		}		
		return -1;
		
    }
}

排名较高的代码

class Solution {
    public int firstUniqChar(String s) {
        int res=-1;
        for(char i='a';i<='z';i++){
            int index=s.indexOf(i);
            if(index!=-1&&index==s.lastIndexOf(i))
                res=(res==-1||res>index)?index:res;
            
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/84922026