Jave one pass solution


  • 1
    C
    public class Solution {
        public int firstUniqChar(String s) {
            int N = s.length();
            int[] count = new int[26];
            int[] pre = new int[N];
            int idx = -1;
            for (int i=N-1; i>=0; i--) {
                char c = s.charAt(i);
                count[c-'a']++;
                if (count[c-'a']==1) {
                    pre[i] = idx;
                    idx = i;
                }
                else if (idx!=-1 && c==s.charAt(idx)){
                    while (idx!=-1 && count[s.charAt(idx)-'a']!=1) {
                        pre[i] = pre[idx];
                        idx = pre[idx];
                    }
                }
            }
            return idx;
        }
    }```

  • 0
    X

    Amazing solution


Log in to reply
 

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