Java Puzzle – Good String / Bad String

1. What is a Good String or Bad String?

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

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

2. Java Program using Regex

Using regex can be a good solution to this problem. I wrote a simple Java program to solve it. It uses the regex '(?i)(\\p{L})\\1'. It matches the two consecutive code points (characters) in a case-insensitive manner. Then it replaces the group with the code point, for which two consecutive chars appeared.

Please feel free to modify the regex as per requirements.

String badString = "Good Oops, Bad Oops";

String goodString = input.replaceAll("(?i)(\\p{L})\\1", "$1");


The program output:

God Ops, Bad Ops

Happy Learning !!

Sourcecode on Github


Notify of
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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode