Skip to content

Latest commit

 

History

History
56 lines (42 loc) · 1.09 KB

387. First Unique Character in a String.md

File metadata and controls

56 lines (42 loc) · 1.09 KB

leetcode-cn Daily Challenge on December 23th, 2020.


Difficulty : Easy

Related Topics : HashTableString


Given a string, find the first non-repeating character in it and return its 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 English letters.

Solution

  • mine
    • Java
      • Runtime: 4 ms, faster than 98.88%, Memory Usage: 39.2 MB, less than 90.15% of Java online submissions
        //O(N)time
        //O(1)space
        public int firstUniqChar(String s) {
            char[] arr = s.toCharArray();
            int[] record = new int[26];
            for(char c : arr){
                record[c - 'a']++;
            }
            for(int i = 0; i < arr.length; i++){
                if(record[arr[i] - 'a'] == 1) return i;
            }
            return -1;
        }