Java 20ms soulution


  • 1
    W
    public class Solution {
        public int firstUniqChar(String s) {
            int array_num[] = new int[26];
            int array_index[] = new int[26];
            char char_array[] = s.toCharArray();
            int length = char_array.length;
            for (int i = 0; i < length; i++) {
                char c = char_array[i];
                array_num[c-'a']++;
                array_index[c-'a'] = i;
            }
            int min_index = -1;
            for (int j = 0; j < array_num.length; j++) {
                if (array_num[j] == 1) {
                    if (min_index != -1) {
                        if (min_index > array_index[j]) {
                            min_index = array_index[j];
                        }
                    } else {
                        min_index = array_index[j];
                    }
                }
            }
            return min_index;
        }
    

  • 0
    S

    Nice solution!!! I had pretty much the exact same :)

    Using underscores instead of camelCase is probably not a big issue (although it goes against convention), but definitely keep the [] with the array's type (i.e. char[] arrName, not char arrName[]). Here's my solution:

    public class Solution {
        public int firstUniqChar(String s) {
            int[] freq = new int[26];
            int[] index = new int[26];
            char[] arr = s.toCharArray();
            for(int i = 0; i < s.length(); i++){
                char c = arr[i];
                freq[c - 'a']++;
                index[c - 'a'] = i;
            }
            int min = -1;
            for(int i = 0; i < freq.length; i++){
                if(freq[i] == 1){
                    min = min != -1 ? Math.min(min, index[i]) : index[i];
                }
            }
            return min;
        }
    }
    

  • 0
    W

    Thanks for your reply! O(∩_∩)O


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.