classsolution459{ publicstaticbooleanrepeatedSubstringPattern(String s){ int n = s.length(); for (int i = 1; i <= n / 2; i++) { if (n % i == 0) { boolean match = true; for (int j = i; j < n; j++) { if (s.charAt(j) != s.charAt(j - i)) { match = false; break; } } if (match) { returntrue; } } } returnfalse; }
publicstaticvoidmain(String[] args) {// main fuction Scanner input = new Scanner(System.in); //比较灵活的输入接受方式 String s = input.nextLine(); boolean result = repeatedSubstringPattern(s); System.out.println(result); input.close(); //最后输入需要关闭 } }
Solution 2: 移位和换行
一个大佬非常秀的解法(醍醐灌顶!),思路如下: 设str = S + S,如果原始字符串由重复子串组成,则str去掉首尾字符之后仍能找到字符串S;反之,则原始字符串不包含重复子串(我没看懂大佬写的题解,所以不知道跟移位有什么关系,我回去再看几遍)。
publicclasssolution6{ publicstaticintupper(int a, int b){ if( a % b == 0){ return a / b; } else { return a / b + 1; } } publicstatic String convert(String s, int numRows){ int n = s.length(); if (numRows == 1 || n <= numRows) { return s; } int nR = upper(n, numRows); int c = (numRows - 1) * nR; char[][] table = newchar[numRows][(int)c]; // Construct 2-dimensional array int T = (numRows - 1) * 2; int x = 0; // row int y = 0; // column for (int i = 0; i < n; i++) { table[x][y] = s.charAt(i); if(i % T < numRows - 1) { x++; } else { x--; y++; } }
// append characters to string StringBuffer str = new StringBuffer(); for (int i = 0; i < numRows; i++) { for (int j = 0; j < c; j++) { if (table[i][j] != 0){ str.append(table[i][j]); } } }
// Construct string String res = new String(str); return res; }
publicstaticvoidmain(String args[]){ Scanner input = new Scanner(System.in); String s = input.nextLine(); int numRows = input.nextInt(); String str = convert(s, numRows); System.out.println(str); input.close(); } }