Search code examples
javastringstringbuilder

How do I compare a rotating StringBuilder with a normal String in Java


Here is the question: Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

For example, if s = "abcde", then it will be "bcdea" after one shift.

  • Input: s = "abcde", goal = "cdeab" Output: true
  • Input: s = "abcde", goal = "abced" Output: false

Here is the code I wrote:

public static void main(String[] args) {

    System.out.println(rotateString("abcd","cdab"));

    }

public static boolean rotateString(String s, String goal) {
        Boolean flag = false;
        StringBuilder builder = new StringBuilder(s);

            for (int i=0;i<=s.length()-1;i++){
            if (builder.toString() == goal) {
                flag= true;
                break;
            }

            char temp = builder.charAt(builder.length()-1);
            for (int j=s.length()-1;j>=0;j--){

                if (j==0) continue;
                builder.setCharAt(j, builder.charAt(j-1));

            }
            builder.setCharAt(0,temp);
            }

        return flag;
    }

I don't know how the flag is still false I also tried debugging it, it shows value of builder.toString() and goal is same.

I was expecting the flag to be true but it always stays false.


Solution

  • "... I don't know how the flag is still false I also tried debugging it, it shows value of builder.toString() and goal is same. ..."

    Since you're comparing String values you'll need to use the equals method.

    If you change the conditional statement to the following, the flag value returns true.

    if (builder.toString().equals(goal))
    

    Additionally, you can rotate the string much simpler.

    public static boolean rotateString(String s, String goal) {
        StringBuilder builder = new StringBuilder(s);
        for (int count = 0; count < s.length(); count++) {
            builder.insert(builder.length(), builder.charAt(0));
            builder.deleteCharAt(0);
            if (builder.toString().equals(goal)) return true;
        }
        return false;
    }