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
题目梗概:不断把A字符串的最后一个字母变成首字母,问移动一定次数后A能否变成B。
解法一
思考:A要变成B,B的首字母一定是在A的某一个位置,那么截取B的首字母与A中字母匹配,当相等时(即a == a),从该字母把A分成两部分,后面部分+前面部分,如果相等那么A经过N步骤会变成B。
func rotateString(_ A: String, _ B: String) -> Bool {
if A == B {
return true
}
var aPartion = -1;
let bSuf = B.prefix(1)
// 寻找a相对于b第一个字母的起始位置
for (index,aChar) in A.enumerated() {
if String(aChar) == bSuf {
aPartion = index
// A以aIndex分割成两部分,后面部分拼接上前面部分
let perA = A.prefix(aPartion)
let sufA = A.suffix(A.count-aPartion);
let rotateA = sufA + perA
if rotateA == B {
return true
}
}
}
return false
}
解法二
思考:A要变成B,那么A+A一定包含B
class Solution {
func rotateString(_ A: String, _ B: String) -> Bool {
if(A.isEmpty && B.isEmpty) {
return true
}
if(A == nil || B == nil) {return false}
if(A.count != B.count) {return false}
let AA = A + A
if(AA.contains(B)) {
return true
}
return false
}
}
网友评论