Simple Java Solution O(n) time


  • 0
    A

    Using an array to store the frequence of character. Get out the first character whose frequence equals 1.

    public class Solution {
        public int firstUniqChar(String s) {
            int[] list = new int[256];
            for (char ch : s.toCharArray()) {
                list[(int)ch] ++;
            }
            for (int i = 0; i < s.length(); i ++) {
                if (list[(int)s.charAt(i)] == 1) return i;
            }
            return -1;
        }
    }
    

Log in to reply
 

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