I'm trying to delete duplicate characters from a string. For example if I enter the string abaqueru
it should give me bqer
with duplicate characters a
and u
deleted. However, instead the result is an unnecessary loop. Here is the code:
public class question {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s = "abaqueru";
calculate(s);
// TODO code application logic here
}
public static void calculate(String s){
String result;
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
char temp;
temp=c;
for(int j = 1; j < s.length(); j++)
{
char x = s.charAt(j);
if(temp==x){
s=s.replaceAll(""+temp,"");
calculate(s);
}
}
System.out.println(s);
}
}
-
don't change your question completely .ask new one if you have a another questionMadhawa Priyashantha– Madhawa Priyashantha2015年08月13日 14:10:07 +00:00Commented Aug 13, 2015 at 14:10
-
Sorry, i didnt know that.Furkan– Furkan2015年08月13日 14:14:20 +00:00Commented Aug 13, 2015 at 14:14
3 Answers 3
String
are immutable in java. After replaceall, you need to assign it back
s=s.replaceAll(""+temp,"");
If you didn't assign it back, the loop goes on forever.
That solves the stackoverflow error, I didn't concentrate on your actual logic :)
1 Comment
I will go with Suresh Atta's Answer which was leading to stack overflow error. I also checked your logic. Have made some necessary changes
public class Question {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s = "abaqueru";
calculate(s);
// TODO code application logic here
}
public static void calculate(String s){
String result;
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
char temp;
temp=c;
for(int j = i+1; j < s.length(); j++)
{
char x = s.charAt(j);
if(temp==x){
s=s.replaceAll(""+temp, "");
break;
// calculate(s);
}
}
}
System.out.println(s);
}
}
However this can be further customized to achive performance in terms of space and time. Infact, more simpler logic can be used :)
Comments
Definitely go with Suresh Atta's answer! However, I figured I'd help glance over your code to help you find where some of your mistakes were.
I just glanced over your logic in the code though, and there is definitely some stuff worth glancing over. The most notable is that j
is never used in the inner-for-loop. In fact, if you are using an IDE, it should warn you that j
is never used.
UPDATE: Also, consider using String.valueOf(char c)
instead of the s=s.replaceAll(""+temp,"");
call you have in the if(temp==x)
condition. That is, I assume that is so you could cast the character to a String? Then you can use String.append(), which you can read about on the link I sent you!
4 Comments
j
in the inner for loop, all 3 character variables will be the same. Notice that you are grabbing the same character each time through the inner for loop, thus comparing it to a character it is guaranteed to be equal to. In other words, you are grabbing the character (at location i
) j
times.