LeetCode-3. Longest Substring Without Repeating Characters

来源:互联网 发布:哪个网络播放器最好用 编辑:程序博客网 时间:2024/06/12 23:05

3.

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.


public class Solution {    public int lengthOfLongestSubstring(String s) {        int length=0;        for(int i=0;i<s.length();i++){            for(int j=1;j<s.length()+1;j++){                if(i>=j){                    continue;                }                if(noRepeatChar(s.substring(i,j))){                    if(j-i>length){                        length=j-i;                    }                }            }        }        return length;    }    private boolean noRepeatChar(String str){        char[] charArr=str.toCharArray();        int [] arr=new int[26];        for(char c:charArr){            arr[c-97]++;        }        for(int i:arr){            if(i>1){                return false;            }        }        return true;    }}

这个解时间复杂度是o(N^3)的样子,TLE是必然的了。这个解假定了输入的字符串只包括a-z,但是也982 / 983 test cases passed了,最后一个test case包括了各种乱七八糟的char,所以有时候会TLE,有时候会数组越界。
慢慢想吧。啊。


这道题花了我两个小时,damn it

public class Solution {    public int lengthOfLongestSubstring(String s) {        HashMap<Character,Integer> map=new HashMap<Character,Integer>();        int max=0;        for(int left=0,right=0;right<s.length();right++){            char c=s.charAt(right);            if(map.containsKey(c)){                int target=map.get(c)+1;                for(int l=left;l<target;l++){                    map.remove(s.charAt(l));                }                left=target;            }            map.put(s.charAt(right),right);            max=Math.max(max,right-left+1);        }        return max;    }}

主要的思路就是用一个map,key存出现过的char,value为他的位置。
然后遍历字符串,如果出现了相同的,就把左指针移到之前出现过相同的char的位置的右一位,然后继续往后找。
啊,语言真的不好形容,还是看代码吧。

0 0
原创粉丝点击