Thursday, December 15, 2016

Find first non-repeating character in String

Following code finds the first non-repeating character in just one pass :)


public class NonRepeating{

public static char firstNonRepeatingChar(String word)
{
Set<Character> repeating = new HashSet<Character>();
List<Character> nonRepeating = new ArrayList<Character>();

for (int i = 0; i < word.length(); i++)
{
char letter = word.charAt(i);
if (repeating.contains(letter))
{
continue;
}

if (nonRepeating.contains(letter))
{
nonRepeating.remove((Character) letter);
        repeating.add(letter);
}
else
{
nonRepeating.add(letter);
}
}

if(nonRepeating.size()!=0)
 return nonRepeating.get(0);
else
  return '\0';
}


public static void main(String[] args)
{
char ans = firstNonRepeatingChar("hrishikesh");

System.out.println("ans="+ans);
}
}

No comments:

Post a Comment

Home