my 4 lines Java solution


  • 8
    public static int firstUniqChar(String s) {
            
    		char[] a = s.toCharArray();
    		
    		for(int i=0; i<a.length;i++){
    			if(s.indexOf(a[i])==s.lastIndexOf(a[i])){return i;}
    		}
    		return -1;
        }

  • 14
    W

    I think the actual complexity will be O(n^2), consider this string: "abcdefghhgfedcba", the total run time will be O(n^2)


  • 10
    H

    I wonder what's the need of using an array?

        public int firstUniqChar(String s) {
            for (int i = 0; i < s.length(); i++) {
                if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) {
                    return i;
                }
            }
            return -1;
        }
    

  • 7
    B

    Hey guys, I don't think interviewers will let us use the built-in String.indexOf() method.


  • 0
    M

    Anyway, I think that was a very cool solution, I like it.


  • 1
    C

    This is O(n^2), will fail u in an interview


  • 0
    E

    Following this toward, you can think in another way like this:
    class Solution {
    public int firstUniqChar(String s) {
    int res = s.length();
    for(char i = 'a'; i <= 'z'; i++){
    int index = s.indexOf(i);
    if(index != -1 && index == s.lastIndexOf(i)){
    res = Math.min(res, index);
    }
    }
    return res == s.length() ? -1 : res;
    }
    }


Log in to reply
 

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