LeetCode – 387. 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 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:

  1. Use an array of booleans to return false if duplicates are found.
  2. If you use a set, and it can't fit anything in, then it's a duplicate.
  3. 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"

143
0 0 143

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top