209 · First Unique Character in a String - LintCode
# Description
Given a string and find the first unique character in a given string. You can assume that there is at least one unique character in the string.
# Example
Example 1:
Input: "abaccdeff"
Output: 'b'
Explanation:
There is only one 'b' and it is the first one.
Example 2:
Input: "aabccd"
Output: 'b'
Explanation:
'b' is the first one.
# Solution
Data stream 簡易寫法
public class Solution { | |
/** | |
* @param str: str: the given string | |
* @return: char: the first unique character in a given string | |
*/ | |
public char firstUniqChar(String str) { | |
List<Character> list = new ArrayList<>(); | |
boolean[] isRepeated = new boolean[256]; | |
for (int i = 0; i < str.length(); i++){ | |
char c = str.charAt(i); | |
if (!isRepeated[c]) { | |
if (list.contains(c)) { | |
list.remove((Character)c); | |
//remove (Object o) ,不強改成 (character) 會 IndexOutOfBoundsException: | |
// 因為 java 會把它轉成 ASCII, a-> 97 | |
// 本來 arraylist remove (index); | |
// 它會以為你 remove 的是在 鏈表裡 index=97 的數 | |
isRepeated[c] = true; | |
} else { | |
list.add(c); | |
} | |
} | |
} | |
return list.get(0); | |
} | |
} |