[leetcode]796. Rotate String旋转字串

时间:2022-11-16 10:15:11

We are given two strings, A and B.

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和B, 问是否能通过旋转使得二者相等

 

Solution1:StringBuilder

 

[leetcode]796. Rotate String旋转字串

直到 A和B 相等,return true, 退出循环

   [leetcode]796. Rotate String旋转字串

 

code

 1 class Solution {
 2     public static boolean rotateString(String A, String B) {
 3         if (A.length() != B.length()) {
 4             return false;
 5         }
 6         if (A.length() == 0) {
 7             return true;
 8         }
 9         StringBuilder sb = new StringBuilder(B);
10 
11         for (int i = 0; i < B.length(); i++) { 
12             if (A.equals(B)) {return true; }
13             char c = sb.charAt(0);
14             sb.deleteCharAt(0);
15             sb.append(c);
16             B = sb.toString();
17         }
18         return false;
19     }
20 }