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 contains only lowercase letters.
There are many similar variations of this type of question, such as:
- Find the first duplicate character
- Confirm that all strings are unique.
The idea is very simple, it's nothing more than:
- Use an array of booleans to return false if duplicates are found.
- If you use a set, and it can't fit anything in, then it's a duplicate.
- Use an array of int, then use string.charAt(i) – 'a', wait for the letter, and then count.
So now I'll use the third method to solve it:
public class Solution { public int firstUniqChar(String s) { int unique[] = new int[26]; for(int i=0;i This websiteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:"LeetCode – 387. First Unique Character in a String"