Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Leen Leenaerts
Leen Leenaerts
1,096 Points

Is this an efficient way of solving this problem?

Is this an efficiënt way of solving this problem? :

Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".

zipZap("zipXzap") → "zpXzp" zipZap("zopzop") → "zpzp" zipZap("zzzopzop") → "zzzpzp"


I solved it this way, but I'm totally new with stringbuilder. I just googled what was the easiest way to delete characters from a string but then i came to the problem that the indices didn't match anymore and I created a counter to solve this problem. Is this the easiest way to solve this problem?

<p>
public String zipZap(String str) {


  StringBuilder sb = new StringBuilder(str);
  int counter = 0;

  for (int i = 0 ; i<str.length()-2 ; i++) {

    if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')  {
    sb.deleteCharAt(i+1-counter);
    counter++;
    }


  }

  return sb.toString();

}
</p>

2 Answers

Michael Hess
Michael Hess
24,512 Points

Hi Leen Leenaerts,

You may want to look into regular expressions. I once had an assignment where part of my problem was finding numbers in a string that matched 0-7 -- regular expressions worked perfectly for this task. It sounds like you also have a problem where you need to find characters that match a certain pattern. Regular expressions are probably the most efficient way to go about doing this.

Oracle Regular Expression Tutorial

Craig Dennis's workshop on Regular Expressions

OCPsoft regex tester

Java Doc for Regular Expressions

Hope this helps!

Michael Hess
Michael Hess
24,512 Points

Yes, that's exactly it!