寻找最长重复(或不重复)子字符串索引(百度笔试题)

1、寻找最长重复子字符串索引,比如:String s = "acbbbb"; 返回索引为2。

//寻找最长重复字符串
public static int selectINdex(String str){
    int start = 0,end = 1,maxStart = 0,maxEnd = 1;
    char[] chars = str.toCharArray();
    for (int i = 1; i < chars.length; i++) {
        if(chars[i-1] != chars[i]){
            end = i;
            int len = end-start;
            if(len>maxEnd-maxStart){
                maxStart = start;
                maxEnd = end;
            }
            //重新计算开始位置
            start = end;
        }
    }
    //返回真实索引
    return start;
}

2、寻找最长无重复子字符串

public static int length(String s){
        if(s.length()==0){
            return 0;
        }
        HashMap map = new HashMap<>();
        int max = 0;
        //最长字串左边界
        int left = 0;
        for (int i = 0; i  
 

你可能感兴趣的:(算法,算法,java,c++)