Longest Substring Without Repeating Characters

来源:互联网 发布:域名真实ip 编辑:程序博客网 时间:2024/06/13 05:31
题目:

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.


最先想到的方法使用map存储字符和index信息,map中不存在字符,则put进来,存在

字符则统计map的size并和存储的最大长度比较,然后清空map。但当测试用例是一个

很长的String时,就会超时。

public static int lengthOfLongestSubstring(String s) {if(s==null)return 0;s=s.trim();int count=0;Map<Character,Integer> map=new HashMap<Character,Integer>();for(int i=0;i<s.length();i++){if(!map.containsKey(s.charAt(i)))map.put(s.charAt(i), i);else{count=Math.max(count, map.size());i=map.get(s.charAt(i));map.clear();}}return Math.max(count, map.size());}

改进的方法是用boolean数组存储字符信息,默认为false,数组中存在字符是,置为true,

否则,记录当前子字符串和count的最大值,将数组置为false,更新子字符串起始index。

public static int lengthOfLongestSubstring(String s){if(s==null||s.length()<=0)return 0;boolean[] ch=new boolean[128];        int start = 0;        int count = 0;        for(int i=0;i<s.length();i++){        if(ch[s.charAt(i)]){//如果数组中不存在字符        count=Math.max(count, i-start);//比较子字符串长度和之前的长度记录        for (int k = start; k < i; k++) {    if (s.charAt(k)== s.charAt(i)) {    start = k + 1; //更新子字符串的起始位置    break;    }    ch[s.charAt(k)] = false;//将数组置为false    }        }else        ch[s.charAt(i)]=true;//将数组中字符对应的位置置为true        }        return Math.max(count, s.length()-start);    }


0 0
原创粉丝点击