The first unique character in the string
Title description: Given a string, find its first unique character, and return its index. If it does not exist, it returns -1.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/first-unique-character-in-a-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Traverse the string
First, if s is null or an empty string, return -1 directly.
If s is only 1, the index bit 0 is returned.
When S length is greater than 1, a statement a LinkedHashMap used to record the number of times each character appears, then traverse S each character, each character and a corresponding number of emerging into a LinkedHashMap in.
LinkedHashMap in order to determine whether there value is 1, that is, a character that has only appeared once. If it exists, return the index bit s If it does not exist after the traversal, -1 is returned.
import java.util.LinkedHashMap;
import java.util.Map;
public class LeetCode_387 {
public static int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
if (s.length() == 1) {
return 0;
}
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : s.toCharArray()) {
if (charCount.containsKey(c)) {
charCount.put(c, charCount.get(c) + 1);
} else {
charCount.put(c, 1);
}
}
for (Map.Entry<Character, Integer> characterIntegerEntry : charCount.entrySet()) {
if (characterIntegerEntry.getValue() == 1) {
return s.indexOf(characterIntegerEntry.getKey());
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(firstUniqChar("loveleetcode"));
}
}
[Daily Message] shines is not necessarily gold, and what is silent is not necessarily stone.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。