796. Rotate String

package LeetCode_796

/**
 * 796. Rotate String
 * https://leetcode.com/problems/rotate-string/description/
 *
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position.
For example, if A = 'abcde', then it will be 'bcdea' after one shift on A.Return True if and only if A can become B after some number of shifts on A.

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.
 * */
class Solution {
    fun rotateString(A: String, B: String): Boolean {
        if (A == B) {
            return true
        }
        var shiftA = A
        for (i in shiftA.indices) {
            //match each string after shift and update shiftA every time
            shiftA = shiftA.substring(1, A.length) + A[i]
            if (shiftA == B) {
                return true
            }
        }
        return false
    }
}

 

posted @ 2020-06-16 13:06  johnny_zhao  阅读(169)  评论(0编辑  收藏  举报