LeetCode-First Unique Character in a String
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.
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(!map.containsKey(c)){
map.put(c,i);
}
else{
map.put(c,-1);
}
}
int max= Integer.MAX_VALUE;
for (Character key : map.keySet()){
int i = map.get(key);
if(i >=0 && i <= max){
max = i;
}
}
if(max == Integer.MAX_VALUE){
return -1;
}
else{
return max;
}
}
}
二刷:
class Solution { public int firstUniqChar(String s) { if(s == null || s.length() == 0){ return -1; } Map<Character, Integer> map = new LinkedHashMap<>(); for(int i= 0; i< s.length(); i++){ char c = s.charAt(i); if(map.containsKey(c)){ map.put(c, -1); } else{ map.put(c,i); } } for(char c : map.keySet()){ if(map.get(c) != -1){ return map.get(c); } } return -1; } }
posted on 2017-12-13 10:10 IncredibleThings 阅读(136) 评论(0) 收藏 举报
浙公网安备 33010602011771号