[leetcode]796. Rotate String旋转字串

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

 

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

   

 

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 }

 

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/10873234.html
0条评论
添加一条新回复
  
今日推荐