387.First Unique Character in a String(文字列の最初の重複しない要素の下付きを返す)
871 ワード
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
Note: You may assume the string contain only lowercase letters.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
import java.util.Hashtable;
public class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> table = new LinkedHashMap<Character, Integer>();
for(char c:s.toCharArray()){
if(table.get(c)==null)
table.put(c, 1);
else{
table.put(c, table.get(c)+1);
}
}
Set<Character> set = table.keySet();
for(char c:set){
if(table.get(c)==1)
return s.indexOf(c);
}
return -1;
}
}