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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

2 thoughts on “Java puzzle : Good String – Bad String”

  1. Solution will not work on more than 2 consecutive chars, need to add “+” quantifier to the end:
    (?i)(\p{L})\1+

    or

    StringBuilder sb = new StringBuilder();
    char prev = Character.UNASSIGNED;
    for (char c : str.toCharArray()) {
    if (prev != c || !Character.isLetter(c)) {
    sb.append(c);
    }
    prev = c;
    }
    return sb.toString();

    Reply
  2. public class Main {
    
        public static void main(String[] args) {
    	    System.out.println("Enter the string you want to convert to a good string");
    
    	    Scanner scanner = new Scanner(System.in);
    	    String s = scanner.nextLine();
            System.out.println("Good string: " + makeIntoGoodString(s));
        }
    
        private static String makeIntoGoodString(String s) {
            String goodString = "";
            if (s != null && s.length() > 0) {
                goodString = goodString + s.charAt(0);
                for (int i = 1; i < s.length(); i++) {
                    if (goodString.charAt(goodString.length() - 1) != s.charAt(i)) {
                        goodString = goodString + s.charAt(i);
                    }
                }
            }
            return goodString;
        }
    
    }
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.