题目描述
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = “leetcode”
return 0.
s = “loveleetcode”,
return 2.
Note: You may assume the string contain only lowercase letters.
思路:
1、用一个布尔数组来标识该数组中的字符是否被访问过,初始化全为false
2、遍历字符数组,若字符被访问过continue,若字符相同,设置被访问过为true
3、遍历完一遍后,发现该字符为被设置为true,则说明没有相同字符,返回下标
注意点,字符串中有可能会有多个相同的字符,如aadadaad,在找到一组相同字符后不可设置break掉。
class Solution {
public int firstUniqChar(String s) {
int index = -1;
char[] chs = s.toCharArray();
boolean[] books = new boolean[chs.length];
for(int i = 0; i < chs.length; i++) {
if(books[i]) {
continue;
}
for(int j = i+1; j < chs.length; j++) {
if(chs[i] == chs[j]) {
books[i] = true;
books[j] = true;
}
}
if(!books[i]) {
index = i;
break;
}
}
return index;
}
}