字符串旋转:
给定两个长度为n字符串A和B,如果能将A从中间某个位置分割为左右两部分字符串(不能为空串),并将左边的字符串移动到右边字符串后面组成新的字符串可以变为字符串B时返回true。
例如:如果A=‘youzan’,B=‘zanyou’,A按‘you’‘zan’切割换位后得到‘zanyou’和B相同,返回true。
再如:如果A=‘abcd’,B=‘abcd’,无法切成两个非空串,使得A换位后可以得到B,返回false。
"abcd","bcda"
true
"abcd","abcd"
false
方法1:暴力
import java.util.*; public class Solution { public boolean solve (String A, String B) { if(A.length() != B.length()) return false; for(int i = 1; i < A.length(); ++i) { if(B.endsWith(A.substring(0, i)) && B.startsWith(A.substring(i))) return true; } return false; } }
方法2:
import java.util.*; public class Solution { public boolean solve (String A, String B) { if(A.length() != B.length()) return false; return (A+A).substring(1, 2*A.length() - 1).contains(B); } }
package main import _"fmt" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 旋转字符串 * @param A string字符串 * @param B string字符串 * @return bool布尔型 */ func solve( A string , B string ) bool { cnt:=0 for { A=A[1:]+A[:1] cnt++ if A==B{ return true } if cnt+1>=len(A){ return false } } return false }
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # 旋转字符串 # @param A string字符串 # @param B string字符串 # @return bool布尔型 # class Solution: def solve(self , A , B ): # write code here if len(A) != len(B): return False for i in range(1,len(A),1): if A[0:i] == B[len(B)-i:] and A[i:] == B[0:len(B)-i]: return True return False
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 旋转字符串 * @param A string字符串 * @param B string字符串 * @return bool布尔型 */ public boolean solve (String A, String B) { // write code here return A.length()==B.length()&&(A+A).substring(1,2*A.length()-1).contains(B); } }