796. Rotate String

# Easy

Solution:

  1. A is original, B is new.

  2. Find all possible start letter position of B corresponded to A.

  3. Then continue comparing following letters bettween A and B.

  4. Consider two edge cases: two strings are empty; two strings contain same letter but different lenght.h

// Java
class Solution {
    public boolean rotateString(String s, String goal) {
        // special case
        if(s.length() != goal.length())
            return false;
        
        // regular case
        int l = s.length();
        for(int i = 0; i < l; i ++) {
            if(s.charAt(i) == goal.charAt(0)) {
                int j = l - i;
                if(s.substring(i).equals(goal.substring(0, j)) 
                  && s.substring(0, i).equals(goal.substring(j)))
                    return true;
            }
        }
        
        return false;
    }
}

Last updated