Repeated String Match(C++重复叠加字符串匹配)

459 篇文章 1 订阅

解题思路:

(1)首先判断字符串B中是否含有字符串A,并判断含有几个A

(2)如果,B中仅有整数n个A,即为所求

(3)如果B中除了含有整数个A外还有首部多余的字符串,此时判断是否与A的尾部匹配,匹配返回n+1,否则返回-1

(4)如果B中除了含有整数个A外还有尾部多余的字符串,此时判断是否与A的首部匹配,匹配返回n+1,否则返回-1

(5)如果B中除了含有整数个A外还有首尾部多余的字符串,此时按照(3)和(4)处理,同时满足返回n+2,否则返回-1

(6)如果,B中不含有A,判断(A+A)是否包含B,是返回2,否则返回-1


class Solution {
public:
    int repeatedStringMatch(string A, string B) {
    	if (A.length()>B.length()) {
    		if (A.find(B)!=string::npos) {
    			return 1;
			} else {
				if ((A+A).find(B)!=string::npos) return 2;
				else return -1;
			}
		}
        int index_i = 0,index_j = 0;
        int count = 0; 
        string s = "";
        index_i = B.find(A); //第一次出现的位置 
		index_j = B.rfind(A); //最后一次出现的位置 
		if (index_i!=string::npos) {
			if ((index_j-index_i)%A.length()!=0) {
				index_i = index_i + A.length() - 1;
			}
			count = (index_j-index_i)/A.length()+1;
			for (int i=0;i<count;i++) { //构建A的重复字符串 
				s+=A; 
			}
			if (s==B.substr(index_i,count*A.length())) {
				if (index_i == 0 && index_j+A.length()==B.length()) { //B正好是A整数倍 
					return count;
				} else {
					if (index_i > 0 && index_j+A.length()==B.length()) { //首部有多余 
						if(judge(A,B.substr(0,index_i),0)) return count+1; //B首部多余部分在A中
						else return -1; 
					} else {
						if (index_i == 0 && index_j+A.length() < B.length()) { //尾部有多余 
							if (judge(A,B.substr(index_j+A.length(),B.length()-index_j-A.length()),1)) return count+1; //B尾部多余部分在A中
							else return -1; 
						} else { //B首尾都有多余 
							 if (judge(A,B.substr(0,index_i),0) && judge(A,B.substr(index_j+A.length(),B.length()-index_j-A.length()),1)) {
							 	return count+2;
							 } else return -1;	 
						} 
					}
				} 
			} else {
				return -1;
			}
			
		} else { //B的中间没有A的重复部分,若是真,只能在两倍A的子串中 
			if ((A+A).find(B)!=string::npos) return 2;
			else return -1;
		}
		
    }
    
    bool judge(string a,string b,int tag=0) { //比较从给定位置起 是否相同 
    	if (a.length()<b.length()) return false;
    	if (tag==0) {
    		int j = a.length()-1;
    		int i = b.length()-1;
    		while(i>=0 && j>=0) {
    			if (a[j]!=b[i]) {
    				return false;
				} else {
					i--;
					j--;
				}
			}
			return true;
		} else {
			int j = 0;
    		int i = 0;
    		while(i<b.length() && j<a.length()) {
    			if (a[j]!=b[i]) {
    				return false;
				} else {
					i++;
					j++;
				}
			}
			return true;
		}
	}
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值