LeetCode-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.

题意:定义对字符串的一次shift为——将字符串最左端的字符与最右端的字符交换位置;现在,给定两个字符串A与B,计算是否可以通过对A进行多次的shift得到字符串B;

解法:要使得A可以通过多次的shift得到字符串B,那么在A中一定可以找到一个位置,从当前位置循环遍历字符串的长度得到的结果就是字符串B;因此,我们只需要遍历字符串A,每次碰到与字符B.charAt(0)相同的字符时,我们进行上述的处理,判断是否可以得到字符串B;

Java
class Solution {
    public boolean rotateString(String A, String B) {
        if (A.length() != B.length()) return false;
        if (A.length() == 0 && B.length() == 0) return true;
        for (int i = 0; i < A.length(); i++) {
            if (A.charAt(i) != B.charAt(0)) continue;
            int index = i;
            boolean right = true;
            for (int j = 0; j < B.length(); j++) {
                if (A.charAt(index % A.length()) != B.charAt(j)) {
                    right = false;
                    break;
                }
                index++;
            }
            if (index - i == B.length() && right) {
                return true;
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值