Loading

无重复字符的最长字串

无重复字符的最长子串

  • 使用HashMap,遍历字符串,将每个字符存入map中。
  • 定义变量left,每次遍历时,使用containsKey判断该字符是否已经存在,若存在且map中取出的i大于left,则令left=i+1,则当前不重复子串长度为i-left+1
  • 定义变量max来表示最长无重复子串,每次循环后,判断max本身与当前遍历的不重复子串i-left+1的大小,令max为最大值。
  • 循环结束后,max的值即为无重复字符的最长字串。
完整代码如下
  public class ReString {
      public static int lengthOfLongestSubstring(String s) {
          if (s.length()==0) {
              return 0;
          }
          HashMap<Character, Integer> map = new HashMap<Character, Integer>();
          int max = 0;
          int left = 0;
          for(int i = 0; i < s.length(); i ++){
              if(map.containsKey(s.charAt(i))){
                  left = Math.max(left,map.get(s.charAt(i)) + 1);
              }
              map.put(s.charAt(i),i);
              max = Math.max(max,i-left+1);
          }
          return max;

      }

      public static void main(String[] args) {
          int i = lengthOfLongestSubstring("abcabcbb");
          System.out.println(i);
      }
  }
  • 时间复杂度O(n),空间复杂度O(1)。
posted @ 2020-07-30 18:10  水纸杯  阅读(195)  评论(0)    收藏  举报