796.Rotate String

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.

Example 1:
Input:
 A = 'abcde', B = 'cdeab'

Output:
 true


Example 2:
Input:
 A = 'abcde', B = 'abced'

Output:
 false

Note:

  • A and B will have length at most 100 .

Solution)

class Solution {
    public boolean rotateString(String A, String B) {
        if (A == null || B == null) return false;
        if (A.length() == 0) return false;
        if (A.length() != B.length()) return false;
        for (int i = 0; i < B.length(); i++) {
            if (A.charAt(0) == B.charAt(i) && A.equals(B.substring(i)+B.substring(0,i))) 
                return true;
        }
        return false;
    }
}

results matching ""

    No results matching ""