给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
class Solution {
public int firstUniqChar(String s) {
int[][] temp=new int[26][2];
int n=s.length();
for(int i=0;i<n;i++){//记录字母出现的次数喝最后一次出现位置temp[s.charAt(i)-'a'][0]++;temp[s.charAt(i)-'a'][1]=i;
}
int res=Integer.MAX_VALUE;
for(int i=0;i<26;i++)if(temp[i][0]==1)//找出只出现一次的字母中,最小的位置{res= Math.min(temp[i][1],res);}
return res==Integer.MAX_VALUE?-1:res;
}
}