题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
代码模板:
class Solution {
public int firstUniqChar(String s) {
}
}
分析
循环这个数组,如果firstindexOf和lastIndexOf是同一个索引,那么也就是说这个字母只出现了一次。
解答
class Solution {
public int firstUniqChar(String s) {
for(int i=0;i<s.length();i++){
if(s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))){
return i;
}
}
return -1;
}
}