我尝试从字符串中删除多处字符, 并仅保留一次( 第一次), 使用循环 。 重复可以是连续的, 也可以是任意的 。
注:我没有使用任何类型的收藏。
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.
这是我试过的密码
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));
}
}