Solved

stringclean challenge

Posted on 2016-09-21
26
54 Views
Last Modified: 2016-09-27
Hi,

I am working on below challenge.
http://codingbat.com/prob/p104029
Psedo code:
1. check the string if length 0  or 1 then retun same str
2.else return string by removing duplicates

I wrote my code as below and not passing all tests
public String stringClean(String str) {
    if(str.length()==0||str.length()==1){
      return str;
    }
    else if(str.charAt(0)==str.charAt(1)){
      return str.charAt(0)+stringClean(str.substring(2));
    }
    else return null;
}

Open in new window


Expected      Run            
stringClean("yyzzza") → "yza"      "yznull"      X      
stringClean("abbbcdd") → "abcd"      null      X      
stringClean("Hello") → "Helo"      null      X      
stringClean("XXabcYY") → "XabcY"      "Xnull"      X      
stringClean("112ab445") → "12ab45"      "1null"      X      
stringClean("Hello Bookkeeper") → "Helo Bokeper"      null      X      
other tests
X      


Any improvements or alternate approaches?      

please advise
0
Comment
Question by:gudii9
  • 14
  • 7
  • 5
26 Comments
 
LVL 27

Expert Comment

by:rrz
Comment Utility
Line 8 of your code returns null. That won't work. You have to return a String.
Line 6 of your code  
      return str.charAt(0)+stringClean(str.substring(2));

Open in new window

 does what step 2 of your pseudo code describes. But, if there is more than two identical adjacent characters, then your code won't know about it. For example,  consider the String  "zzzawq".  The first "z" will be str.charAt(0)  .  You removed the second "z".  Next you call stringClean("zawq") but no knowledge of the first two z's was passed. So, the third "z" will not be removed.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
    if(str.length()<1){
      return str;
    }
    else if(str.charAt(0)==str.charAt(1)){
      return str.charAt(0)+stringClean(str.substring(2));
    }
    else return str.charAt(0)+stringClean(str.substring(1));
}

Open in new window


above failse some tests
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Expected      Run            
stringClean("yyzzza") → "yza"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:5)      X      
stringClean("abbbcdd") → "abcd"      "abbcd"      X      
stringClean("Hello") → "Helo"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:5)      X      
stringClean("XXabcYY") → "XabcY"      "XabcY"      OK      
stringClean("112ab445") → "12ab45"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:5)      X      
stringClean("Hello Bookkeeper") → "Helo Bokeper"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (line number:5)      X      
other tests
X      
Your progress graph for this problem
0
 
LVL 27

Accepted Solution

by:
rrz earned 250 total points
Comment Utility
Originally, you wrote
2:    if(str.length()==0||str.length()==1){
3:      return str;
4:    }

Open in new window

that was logically ok but it could be made more readable. Next you cleaned it up.
    if(str.length()<1){
      return str;
    }

Open in new window

But, that is not  logically equivalent.
You are still removing the second adjacent character. You need the second character to compare to the next character. There might be a third adjacent same character. So, you should be removing the first adjacent character.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
    if(str.length()<2){
      return str;
    }
    else if(str.charAt(0)==str.charAt(1)){
      return str.charAt(0)+stringClean(str.substring(2));
    }
    else return str.charAt(0)+stringClean(str.substring(1));
}

Open in new window


above fails few
Expected      Run            
stringClean("yyzzza") → "yza"      "yzza"      X      
stringClean("abbbcdd") → "abcd"      "abbcd"      X      
stringClean("Hello") → "Helo"      "Helo"      OK      
stringClean("XXabcYY") → "XabcY"      "XabcY"      OK      
stringClean("112ab445") → "12ab45"      "12ab45"      OK      
stringClean("Hello Bookkeeper") → "Helo Bokeper"      "Helo Bokeper"      OK      
other tests
X      
Your progress graph for this problem


please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
    if(str.length()<2){
      return str;
    }
    else if(str.charAt(0)==str.charAt(1)){
      return stringClean(str.substring(1));
    }
    else {
      return str.charAt(0)+stringClean(str.substring(1));
    }
}

Open in new window


above passes all tests.

any improvements or alternate approaches?

how above approach different from below


public String stringClean(String str) {
    if(str.length()<2){
      return str;
    }
    if(str.charAt(0)==str.charAt(1)){
      return stringClean(str.substring(1));
    }
    else {
      return str.charAt(0)+stringClean(str.substring(1));
    }
}

Open in new window


above is preferred or below in case of this challenge or in general?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
both passes all tests
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
As you know by now, there are many ways Java can accomplish the same task. Consider that rather than comparing characters, why not replace first character in the rest of the string with "" (empty string) then recursively pass in the substring starting at the next index until the string length is less than 2 -
if (str.length() < 2 { return str; }
else return str.charAt(0) + str.substring(1).replaceAll(str.charAt(0), "");
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
any improvements or alternate approaches?
No, your code is good.
above is preferred or below in case of this challenge or in general?
In this case the use of the else word is optional because the flow is controlled by the return statements. You can write your code in a way that makes sense to you(and the compiler). But, you should consider readability.  A lot of times we write code and come back to it years later. It is frustrating not being able to understand ones own code.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
   if (str.length() < 2) { 
     return str; 
     
   }
else
{
  return str.charAt(0) + str.substring(1).replaceAll(str.charAt(0), "");
}
}

Open in new window


above gives below error
Compile problems:


Error:      return str.charAt(0) + str.substring(1).replaceAll(str.charAt(0), "");
                                              ^^^^^^^^^^
The method replaceAll(String, String) in the type String is not applicable for the arguments (char, String)


see Example Code to help with compile problems

please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
  if (str.length() < 2){ 
    return str;
    
  }
  if (str.charAt(0) == str.charAt(1))
    {
      return stringClean(str.substring(1));
      
    }
  else
   { 
     return str.charAt(0) + stringClean(str.substring(1));
     
   }
}

Open in new window


above passes all tests. any improvements or alternate approaches?
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Sorry about the compile error. The replaceAll function requires a String for the first parameter and the str.charAt(0) returns a char. Convert the char to a String using the Character.toString() method and it will work. I've split the steps up so you can see what each method is doing.
public static String stringClean(String str) {
	if (str.length() < 2) { 
	     return str;
	} else {
	     String c = Character.toString(str.charAt(0));
	     String s = str.replaceAll(c, "");
	     return c + stringClean(s.substring(1));
	}
}

Open in new window

0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
 else {
	     String c = Character.toString(str.charAt(0));
	     String s = str.replaceAll(c, "");
	     return c + stringClean(s.substring(1));
	}

Open in new window


are we replacing everytime each character with ""?
are not we supposed to do above only if there is repetition of same character as a clean up activity?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 7

Author Comment

by:gudii9
Comment Utility
public static String stringClean(String str) {
	if (str.length() < 2) { 
	     return str;
	} else {
	     String c = Character.toString(str.charAt(0));
	     String s = str.replaceAll(c, "");
	     return c + stringClean(s.substring(1));
	}
}

Open in new window


above giving below error


Error:Bad code
Common problems: code should not use println or class or static or exceptions

please advise
0
 
LVL 31

Assisted Solution

by:awking00
awking00 earned 250 total points
Comment Utility
Remove the static keyword.
>>are we replacing everytime each character with ""?
 are not we supposed to do above only if there is repetition of same character as a clean up activity?
<<
c is the first character as a String, So replaceAll() replaces all of those characters with an empty string but you return the character c +  a new result for stringClean passing in a substring that begins with a new character.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
public String stringClean(String str) {
	if (str.length() < 2) { 
	     return str;
	} else {
	     String c = Character.toString(str.charAt(0));
	     String s = str.replaceAll(c, "");
	     return c + stringClean(s.substring(1));
	}
}

Open in new window



above gives below error

Expected      Run            
stringClean("yyzzza") → "yza"      "yz"      X      
stringClean("abbbcdd") → "abcd"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)      X      
stringClean("Hello") → "Helo"      "Hl"      X      
stringClean("XXabcYY") → "XabcY"      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7)      X      
stringClean("112ab445") → "12ab45"      "1a4"      X      
stringClean("Hello Bookkeeper") → "Helo Bokeper"      "Hl oker"      X      
other tests

please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
why we chose only c why not z or x etc?


public static String stringClean(String str) {
      if (str.length() < 2) {
           return str;
      } else {
           String c = Character.toString(str.charAt(0));
           String s = str.replaceAll(c, "");
           return c + stringClean(s.substring(1));
      }
}



>>are we replacing everytime each character with ""?
  are not we supposed to do above only if there is repetition of same character as a clean up activity?<<
 c is the first character as a String, So replaceAll() replaces all of those characters with an empty string but you return the character c +  a new result for stringClean passing in a substring that begins with a new character. code]
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
You can call it anything you like -
String thisIsTheStringThatRepresentsTheFirstCharacterInTheStringThatIWantToKeep = Character.toString(str.charAt(0));
String s = str.replaceAll("thisIsTheStringThatRepresentsTheFirstCharacterInTheStringThatIWantToKeep","");
return thisIsTheStringThatRepresentsTheFirstCharacterInTheStringThatIWantToKeep + stringClean(s.substring(1));
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
is just variable name not the character we chose from str.

public String stringClean(String str) {
	if (str.length() < 2) { 
	     return str;
	} else {
	     String c = Character.toString(str.charAt(0));
	     String s = str.replaceAll(c, "");
	     return c + stringClean(s.substring(1));
	}
}

Open in new window



Expected

Run



stringClean("yyzzza") → "yza" "yz" X  
stringClean("abbbcdd") → "abcd" Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7) X  
stringClean("Hello") → "Helo" "Hl" X  
stringClean("XXabcYY") → "XabcY" Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:7) X  
stringClean("112ab445") → "12ab45" "1a4" X  
stringClean("Hello Bookkeeper") → "Helo Bokeper" "Hl oker" X  

other tests
 X
above fail belw tests. please advise
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
@awking00, you better rethink your code. The  replaceAll  method isn't helpful for this challenge. You only want to remove adjacent chars.
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
line 7  
	     return c + stringClean(s.substring(1));

Open in new window

should be
	     return c + stringClean(s);

Open in new window

after making that change, you will see my point above.
0
 
LVL 31

Expert Comment

by:awking00
Comment Utility
Wow! I totally misread the challenge :-( Thanks, rrz, for pointing out the error of my ways.
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
@awking00, I have been there. I think we all have been there.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
How to fix above code to make work in experts exchange?
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
How to fix above code to make work in experts exchange?
Are you referring to the code that awking00 posted? If yes, then I don't see how. The replaceAll method will remove all the characters of the String that match the supplied argument  instead of just the  adjacent characters.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Me too not sure
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now