LeetCode 459. 重复的子字符串 重复的字串模式 Repeated Substring Pattern

参考:

  • https://blog.csdn.net/qq_36387730/article/details/81661315
  • KMP 九章算法:重复的子串模式
  • 招银信用卡2018春招(第一批)题解
import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {
	static Scanner sc = new Scanner(new BufferedInputStream(System.in));

	public static void main(String[] args) {
		while (sc.hasNext()) {
			String str = sc.next();// 读入
			if(str.length()<=1) {
				System.out.println("false");
				continue;
			}
			boolean flag = false;
			String sub="";
			for (int subLen = str.length() / 2; subLen > 0; subLen--) {
				if (str.length() % subLen == 0) {
					StringBuilder sBuilder = new StringBuilder();
					String temp = str.substring(0, subLen);
					int n = str.length() / subLen;// 子串个数
					for (int i = 0; i < n; i++) {
						sBuilder.append(temp);
					} // 构建好子串
					if(str.equals(sBuilder.toString())){// 与原来的字符串相同
						flag = true;
						sub =temp;
					}
				}
			}
			
			if (flag) {
				System.out.println(sub);
			} else {
				System.out.println("false");
			}
		}

	}
}

你可能感兴趣的:(java)