Java puzzle : Good String – Bad String

Puzzle: Chandu is very fond of strings. (Or so he thinks!) But, he does not like strings which have same consecutive letters. No one has any idea why it is so. He calls these strings as Bad strings. So, Good strings are the strings which do not have same consecutive letters. Now, the problem is quite simple. Given a string S, you need to convert it into a Good String.

You simply need to perform one operation – if there are two same consecutive letters, delete one of them.

Solution

I believe that using regex would be only good solution for this problem. I wrote a sample program to solve it. Please feel free to modify the regex as per requirements.

public class GoodStringBadString
{
    public static void main(String[] args)
    {
        String input = "Good Oops, Bad Oops";
        String output = input.replaceAll("(?i)(\\p{L})\\1", "$1");
        System.out.println(output);
    }
}
Output: God Ops, Bad Ops

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.