Java求字符串的最大子串和长度

之前在面试的时候遇到过的一个问题,由于当场让手写(特别反感这种面试中要求手写的),就没理会,回来想想看看能不能实现,今天有时间写出来,让大家帮忙指正。
题目是给出一个字符串计算出它的最大子串
例: “abcdefgabc” -> abcdefg
“ababcdeac” -> abcde
代码在下面,加了注释

/**
 * 求字符串的最大子串
 * 
 * @ClassName: App
 * @Description: 思路是定义一个头指针和一个尾指针,头尾指针都从0开始,并用256的数组散列保存之前出现过的字符。
 *               尾指针率先向前移动,每移动一次,将移动的字符对应的数组下标置为1,当尾指针到底字符串末尾则完毕,如果在循环内下次移动尾指针前发现字符在数组中出现过,则说明出现重复,移动头指针,在移动的过程中将路径中的数组置为0.
 * @author: Levin
 * @date: 2017年9月1日 下午4:33:58
 */
public class getMaxSubString {
    public static void main(String[] args) {
        char[] str = "ababcdeac".toCharArray();
        // i为头指针,j为尾指针
        int i = 0, j = 0;
        // 保存最大的字符串出现的下标
        int max_i = 0, max_j = 0;
        // 散列数组
        int hash[] = new int[256];
        int length = str.length;
        int maxlength = 0;
        while (j < length) {
            // 如果尾指针在散列中出现
            if (hash[(int) str[j]] == 1) {
                // 正好头指针和尾指针值相同
                if (str[i] == str[j]) {
                    hash[(int) str[i++]] = 0;
                } else {
                    // 头指针与尾指针路径中间存在与尾指针相同值的,直接跳到与尾指针相同值的下一个位置
                    while (str[i] != str[j]) {
                        hash[(int) str[i++]] = 0;
                    }
                    i++;
                }
            }
            // 将尾指针路过的字符串放到散列中
            hash[(int) str[j]] = 1;
            j++;
            if (j - i > maxlength) {
                maxlength = j - i;
                max_i = i;
                max_j = j;
            }
        }
        maxlength = maxlength > (j - i) ? maxlength : (j - i);
        System.out.println("最大子串长度"+maxlength);
        System.out.println(Arrays.copyOfRange(str, max_i, max_j));
    }

}

猜你喜欢

转载自blog.csdn.net/q2365921/article/details/77776050