We are given two strings,AandB.

A_shift onA_consists of taking stringAand moving the leftmost character to the rightmost position. For example, ifA = 'abcde', then it will be'bcdea'after one shift onA. ReturnTrueif and only ifAcan becomeBafter some number of shifts onA.

class Solution {
    public boolean rotateString(String A, String B) {
        if(A == null && B == null)
            return true;
        if(A == null || B == null)
            return false;

        if(A.length() != B.length())
            return false;

        if(A.equals(B))
            return true;

        int j = 0;

        while(j < B.length()) {
            while(j < B.length() && B.charAt(j) != A.charAt(0))
                j++;

            int i = 0;
            for(; i < A.length(); i++) {
                if(j + i < B.length()) {
                    if(A.charAt(i) != B.charAt(i + j))
                        break;
                } else {
                    if(A.charAt(i) != B.charAt((i + j) % (B.length())))
                        break;
                }
            }
            if(i == A.length())
                return true;

            j++;
        }

        return false;
    }
}

results matching ""

    No results matching ""