Problem Statement :
Print the first non repeating character in a string.
Example :
In the string
somecharsjustdon'tliketorepeat
,m
is the first non-repeating charecter.
My attempt :
New Code : Old one was not working as expected so I have updated the post. Old code can be found below new code
public class FirstNonRepeatedChar{
static boolean isRepeated(String str, char c){
int count = 0;
for(char ch: str.toCharArray()){
if(c == ch){
count++;
}
}
return count > 1;
}
static void printFirstNonRepeatedChar(String str){
boolean found = false;
for(char c : str.toCharArray()){
if(! isRepeated(str, c)){
found = true;
System.out.println(str + " : " +c);
break;
}
}
if(!found){
System.out.println(str + " : No non-repeated char");
}
}
public static void main(String [] args){
String []testCases = {"aaabbcc", "sss", "121", "test", "aabc"};
for(String str: testCases){
printFirstNonRepeatedChar(str);
}
}
}
Old code
public class FirstNonRepeatedChar{
public static void main(String [] args){
String str = "somecharsjustdon'tliketorepeat";
loopI:
for(int i = 0;i<str.length();i++){
for(int j = i+1; j<str.length();j++){
if(str.charAt(i)==str.charAt(j))
continue loopI;
}
System.out.println(str.charAt(i));
break;
}
}
}
I want to ask :
- Is there better way to solve this problem? Especially, is there efficient way to do this using built-in classes?
- Can I reduce complexity?
- Is there any case where my code may fail to generate appropriate result? and how can I avoid these failures?
Thanks in advance!
abab
orababx
. Your alrogithm outputsa
for both of them, where no output andx
is expected respectively. Use an ordered map<char, count> to count the occurences of each character, then lookup the first character whose occurence is 1. \$\endgroup\$