判断字符串是否可由子串拼接而成

判断字符串是否可由子串拼接而成

题目描述:输出最长子串,该子串首尾相连可以形成原字符串(笔试题)。

Exp:

输入:abcabcabc

输出:abc

否则输出 false

#include<iostream>
#include<string>
using namespace std;
int main(){
	string s;
	cin >> s;
	int length = s.size();
	int len = (length+1) / 2;
	int i, j;
	for (i = len-1; i >= 0; i--){
		for (j = i+1; j < length; j++){
			if (s[j] == s[j % (i+1)]){
				continue;
			}
			else{
				break;
			}
		}
		if (j == length&&(j-1)%(i+1)==i){
			break;
		}
	}
	if (i < 0){
		cout << false;
	}
	for (int t = 0; t < i + 1; t++){
		cout << s[t];
	}
	system("pause");
}

Java版本:

package com.test;

public class Test409 {
	public static void duplicate(String s){
		if(s==null||s.length()<1){
			return;
		}
		int len=(s.length()+1)/2;
		int i,j;
		for(i=len-1;i>=0;i--){
			for(j=i+1;j<s.length();j++){
				if(s.charAt(j)==s.charAt(j%(i+1))){
					continue;
				}
				else{
					break;
				}
			}
			if(j==s.length()&&(j-1)%(i+1)==i){
				break;
			}
		}
		if(i<0){
			System.out.println("false");
		}
		for(int t=0;t<i+1;t++){
			System.out.print(s.charAt(t));
		}
	}
	public static void main(String[] args){
		duplicate("abceabce");
	}

}



猜你喜欢

转载自blog.csdn.net/heart_leader/article/details/79853557