LeetCode 3. 无重复字符的最长子串(Java版)

原题题解

方法一

穷举所有的子串(定义两个函数):

      ①第一个函数穷举所有可能出现的子串结果,对于字符串的每一个字符,它所构成的子串是下标比它大的所有子串组合

            eg:abc

              对于a,子串有a, ab,abc,

              对于b,子串有b,bc,

              对于c,有子串c

          所以字符串abc的所有的子串为a,ab,abc,b,bc,c

       ②第二个函数用户过滤穷举出来的子串是否重复,用hashset


时间复杂度o(n^3)这种方法会超时

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int res=0;
  4. for(int i=0;i<s.length();i++){
  5. for(int j=i+1;j<=s.length();j++){
  6. if(isTrue(s,i,j))
  7. res=Math.max(res,j-i);
  8. }
  9. }
  10. return res;
  11. }
  12. public boolean isTrue(String s ,int start,int end){
  13. Set<Character> set=new HashSet<>();
  14. for(int i=start;i<end;i++){
  15. if(set.contains(s.charAt(i)))
  16. return false;
  17. set.add(s.charAt(i));
  18. }
  19. return true;
  20. }
  21. }

方法二

   滑动窗口法:

          定义两个指针,start和end,代表当前窗口的开始和结束位置,同样使用hashset,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值


时间复杂度o(n)

  1. public class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int n = s.length();
  4. int res = 0;
  5. int end=0,start=0;
  6. Set<Character> set=new HashSet<>();
  7. while(start<n && end<n){
  8. if(set.contains(s.charAt(end))){
  9. set.remove(s.charAt(start++));
  10. }else{
  11. set.add(s.charAt(end++));
  12. res=Math.max(res,end-start);
  13. }
  14.  
  15. }
  16. return res;
  17. }
  18.  
  19.  
  20. }

方法三

      由方法二得到的滑动窗口,每次在[start,end]中如果有重复的,我们的做法是更新窗口从end重新开始,这种方法要求定义一个hashmap保存字符到索引的映射,并且每次都会更新map的值


时间复杂度o(n)

  1. public class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int n = s.length();
  4. int res = 0;
  5. int end=0,start=0;
  6. Map<Character,Integer> map=new HashMap<>();
  7. for(;start<n && end<n;end++){
  8. if(map.containsKey(s.charAt(end))){
  9. start=Math.max(map.get(s.charAt(end)),start);//从有重复的下一个位置继续找
  10. }
  11. map.put(s.charAt(end),end+1);//map每次更新
  12. res=Math.max(res,end-start+1);//结果每次更新
  13. }
  14. return res;
  15. }
  16. }
  17. /*
  18. eg abca
  19. start end res map 滑动窗口范围
  20. 0 0 1 a->1 a
  21. 0 1 2 a->1,b->2 a,b
  22. 0 2 3 a->1,b->2,c->3 a,b,c
  23. 1 3 3 a->4,b->2,c->3 b,c,a
  24. */
posted @ 2019-07-06 11:46  天涯海角路  阅读(150)  评论(0)    收藏  举报