【LeetCode】796. Rotate String

题目:


思路:这道题目关键在思路吧,没什么想法的话,这里先给一个提示:string str = A + A,先思考一下然后再看答案代码。

下面贴代码,一些解释写在代码注释里

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

class Solution {
public:
    bool rotateString(string A, string B) {
        if(A.length() != B.length())
			return false;
		else{
			string str = A + A;
			int len = B.length();
			for(int i = 0; i < len; i++){
				int j = 0;
				if(str[i] == B[j]){ //首先这里找到B的第一个字母在A中的位置
				while(j < len){
					if(str[i+j] == B[j])
						j++; //这里是要判断是否B完全在A+A中
					else break;//在else中,要及时跳出循环,避免死循环
				}
				if(j == len) return true;//这里用来判断,跳出循环是因为j加到了B.length()还是因为str[i+j] != B[j]
				}
			}
		return false;
		}
    }
};

int main(){
	Solution so;
	string A = "abcde";
	string B = "abced";
    cout << so.rotateString(A,B) <<endl;
		system ("pause");
		return 0;
}


还有一种解法是利用基本函数substr,

这里对substr做一个说明:

例如:

string s = "asdfghjkl ";

substr sub1 = s(1); //表示从下标1开始至结束 即sub1 = "sdfghjkl";

substr sub2 = s(1,4); //表示从下标1开始,截取4个字符,即sub2 = "sdfg";

substr sub3 = s(7,5); //表示从下标8开始截取5个字符,但剩余字符少于5个,则截取至结束,即sub3 = "kl";

class Solution {
public:
    bool rotateString(string A, string B) {
        if(A.length() != B.length())
			return false;
		else{
			int len = A.length();
			for(int i = 0; i < len; i++)
				if(A.substr(i,len)+A.substr(0,i) == B)
					return true;
			return false;
		}
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值