9.8号JD笔试

编程题

给定一个字符串s,请计算输出含有连续两个s 作为子串的最短字符串。注意两个字符串可能会有重叠部分。例如:“ababa”含有两个“aba”。

输入用例:abracadabra

输出结果:abracadabracadabra


实现代码:

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

int main(){
	string s;
	int i,j,cnt,len;
	while(cin>>s){
		string temp(s);
		string result;
		len=s.size();
		//当输入字符串个数只长度为1时
		if(len==1){
			result+=s;
			result+=s;
			cout<<result<<endl;
			result.clear();
		}
		else{
			//当输入字符串大于1时 
			//判断字符串最后面有无子串与字符串最前面的子串重合 
			for(i=0,j=len/2;i<len&&j<len;){
	         	if(s[i]==s[j]){
	     		  i++;
	    		  j++;
	    	    }
	    	    else{
	    	    	j++;
	    	    	if(i!=0)
		        	  i--;    	
		        }
	       }
	       //没有重合情况 
	       if(i==0)
	       {
	        	result+=temp;
	         	result+=temp;
	        	cout<<result<<endl;
	        	temp.clear();
	            result.clear();
	        }
	        else{
	        	//有重合情况 
	        	cnt=i+1;
    	        len=len-cnt;
             	for(i=0;i<=len;i++)
    	           result=result+s[i];
    	        result=result+temp;
    	        cout<<result<<endl;
	            temp.clear();
	            result.clear();
	        }
	    
			
		}
    	
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/cnd2449294059/article/details/77899236
9.8