Simple solution 27ms worst case O(n^2) time and no extra space


  • 0

    Using the indexOf at each step returns if there is the same character after this and checking again ensures that we have not passed it.

            char [] charr = s.toCharArray();
    		for(int i=0;i<charr.length;i++){
    			if(s.indexOf(s.charAt(i), i+1) == -1 ){
    			if(s.indexOf(s.charAt(i)) == i){
    				return i;
    			}
    			}
    		}
    		return -1;
        }

  • 0
    K

    This is O(n^2). Each call to indexOf has to iterate the rest of the string.


  • 0

    @kyle33 Thanks!! That is true. Just realized. Some how assumed that cause of only one loop. Forgot about the index of. Ill change the solution to say so.


Log in to reply
 

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