1 package ren.laughing.test.problem;
2
3 import java.util.Scanner;
4
5 /**
6 * 功能:判断一个数字中是否包含两个相同的子串(字串长度至少大于等于2),并输出(仅输出第一次相同的子串)
7 *
8 * @author Laughing_Lz
9 * @time 2016年7月4日
10 */
11 public class ChildStr {
12 private String str;
13
14 /**
15 * 判断输入字符串是否合法
16 */
17 public void input() {
18 Scanner sc = new Scanner(System.in);
19 str = sc.nextLine();
20 sc.close();
21 if (str.isEmpty()) {// 若是输入为空
22 str = null;
23 return;
24 }
25 for (int i = 0; i < str.length(); i++) {
26 char c = str.charAt(i);
27 if (str.isEmpty() || !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) {// 限制条件
28 str = null;
29 return;
30 }
31 }
32 }
33
34 /**
35 * 查找算法
36 */
37 public void search() {
38 if (str == null) {
39 System.out.println("输入字符串错误!");
40 return;
41 }
42 int j = 1;// 此处将index定义在两个循环外,可实如今一次循环中j始终和i同步递进★
43 int number = 0;// 记录相同子串长度
44 int index = 0;// 记录字串起始位置
45 for (int i = 0; i < str.length() - 1; i++) {
46 char numi = str.charAt(i);// 当前位置数字
47 if (i == str.length() - 2 || j == str.length()) {
48 number = 0;// 将number归0
49 j = i + 1;// 一次循环后,将j移回i+1起始点,再次遍历
50 }
51 for (; j < str.length(); j++) {
52 char numj = str.charAt(j);
53 if (numi == numj) {
54 number++;
55 if (j < str.length() - 1) {
56 j++;// 判断下个数字前将j++
57 }
58 break;
59 } else {
60 if (number >= 2) {
61 break;
62 } else {
63 number = 0;// 若仅遇到1位数字相同,在遇到不一样数字时,将number置0
64 }
65 }
66 }
67 if (number >= 2 && str.charAt(i + 1) != str.charAt(j)) {// 当相同数字已大于2后,遇到不一样数字当即退出循环,打印子串
68 index = i + 1;
69 break;
70 }
71 }
72 if (number >= 2) {
73 System.out.println("存在,字串为:" + str.substring(index - number, index));
74 }
75 }
76
77 public static void main(String arg[]) {
78 ChildStr cs = new ChildStr();
79 cs.input();
80 cs.search();
81 }
82 }