I tried removing multiple occurrences of characters from a string and keep only one occurrence using recursion.
e.g. Input:- RAMA, Output:- RAM i.e It removed only second occurrence of char ‘A’ and printed ‘RAM’.
I am getting stuck at calling recursive function ‘remove’ with stack values as it is always being called with same value ‘A’. Please review once.
Here is the code which I tried.
class RecursionRemoveDuplicatesFromString {
String newStr="";
String subs = "";
String remvDupl = "";
int i = 0;
int j = 0;
int count = 0;
String removeDuplicates(String toSubs){
//String toSubs = s;
if(toSubs.length()==1){
return toSubs;
}
if(i <= toSubs.length()-2){
subs = toSubs.substring(i,i+1);
}else{
subs = toSubs.substring(i);
return subs;
}
//String subs = i <= toSubs.length()-2 ? toSubs.substring(i,i+1) : return toSubs.substring(i,i+1);
i++;
System.out.println(subs);
removeDuplicates(toSubs);
//System.out.println(subs);
remove(toSubs,subs);
return newStr;
}
void remove(String s, String subs){
if(s.length()==1){
return;
}
while(j<s.length()){
if(j <= s.length()-2){
remvDupl = s.substring(j,j+1);
}else{
remvDupl = s.substring(j);
//return remvDupl;
}
//String remvDupl = j < s.length()-2 ? s.substring(j,j+1) : "";
if(remvDupl.equalsIgnoreCase(subs)){
count += 1;
//newStr += subs;
if(count==1){
newStr += subs;
}
}
j++;
}
//remove(s, remvDupl);
count = 0;
}
public static void main(String[] args) {
String s = "RAMA";
RecursionRemoveDuplicatesFromString remvDupli = new RecursionRemoveDuplicatesFromString();
System.out.println(remvDupli.removeDuplicates(s));
}
}