-
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
-
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
public class Solution_1 {
public int firstUniqChar(String s) {
char[] ch = s.toCharArray();
for(int i = 0;i<ch.length;i++) {
boolean isUnique = true;
for(int j = 0;j<ch.length;j++) {
if(i != j&&ch[i] == ch[j]) {
isUnique = false;
break;
}
}
if(isUnique) {
System.out.println(i);
return i;
}
}
return -1;
}
public static void main(String[] args) {
String str = "loveleetcode";
Solution_1 solution = new Solution_1();
solution.firstUniqChar(str);
}
}
第二种:
public class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> map = new LinkedHashMap<Character,Integer>();
char[] ch=s.toCharArray();
for(int i = 0;i<ch.length;i++) {
if(!map.containsKey(ch[i])) {
map.put(ch[i], i);
}
map.put(ch[i], -1);
}
for(Map.Entry<Character,Integer> entry : map.entrySet()) {
if(entry.getValue() != -1) {
return entry.getKey();
}
}
return -1;
}
public static void main(String[] args) {
String str = "leetcode";
Solution solution = new Solution();
solution.firstUniqChar(str);
}
}