Longest Substring Without Repeating Characters

来源:互联网 发布:会计软件单机版 编辑:程序博客网 时间:2024/06/08 07:52

原理: 历遍字符串,查看当前字符是否出现过,当出现过的时候,子串开始位置+1,否则更新locs数组中的地址值为当前位置。

public class Solution {

    public int lengthOfLongestSubstring(String s) {
        int[] locs = new int[256];
        int index = 0;
        int idx = -1;
        int max  =0;
        long pretime;
        long endtime;
        for(int i = 0; i < locs.length; i++){
            locs[i] = -1;
        }
        for( index = 0; index < s.length(); index++){
            if(locs[(int)s.charAt(index)] > idx){ // 说明这个字符出现过
                idx = locs[s.charAt(index)];
            }

            if(index - idx > max){
                max = index - idx;
            }

            locs[s.charAt(index)] = index;
        }
        
        return max;
    }
}
0 0
原创粉丝点击