Java solution with easy-understanding explanation


  • 0
    P

    The program works as following:
    Take the string: idontlikeleetcode for an example,
    char c[] = s.toCharArray();
    First, pick up those characters that appear more than one time and store them in the Hashset.
    Now the Hashset contains: i,d,o,n,t,l,k,e,c. And when we pick these characters out from idontlikeleetcode, swap those characters with ' ',
    We can get the char array c: _ _ _ _ _ i _leet_ode.
    Second, if char array c still consists characters in the set, for example, i,e,t,o,d,l. it means that these characters appeared more than once. So we can remove them from the Hashset.
    Then we get the characters which only appeared once in the Hashset: n,k,c.
    Finally, we just need to output the index of the first character 'n', that's all.

    public class Solution {
    public int firstUniqChar(String s) {
    if(s == null)
    {
    return -1;
    }
    char[] c = s.toCharArray();
    char[] copy = s.toCharArray();
    HashSet set = new HashSet();
    //first, get all characters that was appeared at least once. Store them in set.
    for(int i = 0;i<c.length;i++)
    {
    if(!set.contains(c[i]))
    {
    set.add(c[i]);
    c[i] = ' ';//delete those characters in c[i]
    }
    }
    //Second, if c[i] still contains characters in set, remove them in set.
    for(int i = 0;i<c.length;i++)
    {
    if(set.contains(c[i])&&c[i]!=' ')
    {
    set.remove(c[i]);
    }
    }
    //third, output the first unique character remain in set.
    for(int i = 0;i<copy.length;i++)
    {
    if(set.contains(copy[i]))
    {
    return i;
    }
    }
    return -1;

    }
    

    }


Log in to reply
 

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