LeetCode 796 Rotate String

21 篇文章 0 订阅
20 篇文章 0 订阅

LeetCode 796 Rotate String

传送门:LeetCode 796

题目分析

题目原文:

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

题目就是一个字符串经过移位操作操作与另一个字符串相等,类似循环移位,判断给定的两个字符串是否满足这种关系。

思考

题目的要求很简单,对一个字符串进行移位操作来使其与另一个字符串相等,移位操作让我想到了使用循环队列的操作,把队头的元素加到队尾,判断是否相等,思路就是使用循环队列的思想进行比较,时间复杂度应该是O( O2 O 2 )。

代码实现

using ull = unsigned long long;

class Solution {
public:
    bool rotateString(string A, string B) {
        if (A.length() != B.length()) {
            return false;
        }
        ull length = A.length();
        // 旋转判断
        for (int i = 0; i < length; ++i) {
            bool same = true;
            for (int j = 0; same && j < length; ++j) {
                if (A[j] != B[(j + i) % length]) {
                    same = false;
                }
            }
            // 相同返回true
            if (same) {
                return true;
            }
        }
        // 移位全部试探失败
        return false;
    }
};

感想

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值