leetCode 3. Longest Substring Without Repeating Characters 解法与思路

来源:互联网 发布:图书销售软件 编辑:程序博客网 时间:2024/06/05 14:24

问题:

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路:

在开始解题的时候用快排的思想,首尾双指针扫描,本地少量字符测试,效果良好。

public class Solution {public int lengthOfLongestSubstring(String s) {        int i = 0;//字符串起始位置        int j = s.length() - 1;//字符串结束位置        //类似快排的思想,双线扫描        boolean isBegin = false;//是否已扫描到子串开头        boolean isEnd = false;//是否已扫描到子串结尾        while(i < j){        //从右往左扫描,如果当前字符在之前含有,则j--;没有,跳出循环            while(i < j ){            String s1 = s.substring(0,j);            System.out.println(s1 +"  --  " +  s.charAt(j));            if(s1.indexOf(s.charAt(j)) > -1){            j--;            isBegin = false;            }            else{            isBegin = true;            break;            }            }            System.out.println(" j --  " +  j);                        //从左往由扫描,如果当前字符在之后含有,则i++;没有,跳出循环            while(i < j ){            String s2 = s.substring(i+1,j);            System.out.println(s2 + "  --  " +  s.charAt(i));            if(s2.indexOf(s.charAt(i)) > -1){            i++;            isEnd = false;            }            else{            isEnd = true;            break;            }            }            System.out.println(" i --  " +  i);            //当即是开头也是结尾时,说明扫描到最大子串,返回            if(isBegin && isEnd){            break;            }        }return j - i + 1;//返回最大长度    }}

但是有个最大的问题,就是效率太低,最好提交时果断超时。最后上网查看资料,最后将c/c++解法理解之后,改为了java代码,顺利通过。

思想很重要。

最后的代码:

public class Solution {public int lengthOfLongestSubstring(String s) {        int[] locs = new int[128];//保存字符上一次出现的位置ASCII码共128个字符,所以要128才行        Arrays.fill(locs, -1);//数组初始化-1        int idx = -1, max = 0;//idx为当前子串的开始位置-1        for (int i = 0; i < s.length(); i++)        {            if (locs[s.charAt(i)] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1            {                idx = locs[s.charAt(i)];            }            if (i - idx > max)            {                max = i - idx;            }            locs[s.charAt(i)] = i;        }        return max;    }}


0 0