Java Puzzle – Good String / Bad String

Good strings do not have the same consecutive letters. We simply need to perform one operation – if there are two same consecutive letters, delete one.

Java Interview Puzzles

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");

System.out.println(output);

The program output:

God Ops, Bad Ops

Happy Learning !!

Sourcecode on Github

Leave a Comment

  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

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.