zoukankan      html  css  js  c++  java
  • LeetCode 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.

    思路:1.将每组子串的字母存在hashset中,判断当前字母是否存在set中(hash查找效率高)。

    2.若存在则判断下一组子串。下组子串的初始位置在重复字母处位置+1。

    3.若不存在则将此字母存在容器中,并判断当然容器大小是不是最大, 若是最大表示当前长度最大。

    如abcabcbb,

    1.容器中一次存入第一个子串abc,到第2个a事与第一个a重复,容器中移除第一个a到第一个子串的初始位置0的所有元素,容器中的元素为abc。

    2.容器中子串bca,第二个b重复,相同办法。

    注:判断下个子串的初始位置,为重复字母的位置+1,类似于kmp算法。

     1 public int lengthOfLongestSubstring(String s) {
     2         int max = 0;
     3         int flag = 0;
     4         Set<Character> set = new HashSet<Character>();
     5         char[] a = s.toCharArray();
     6         for(int i=0;i<a.length;i++) {
     7             if(!set.contains(a[i])) {
     8                 set.add(a[i]);
     9                 if(max<set.size()) {
    10                     max = set.size();
    11                 }
    12             }else {
    13                 int j = flag;
    14                 while(a[i]!=a[j]) {
    15                     set.remove(a[j]);
    16                     j++;
    17                 }
    18                 flag = j+1;
    19             }
    20             //System.out.println(set.toString());
    21         }
    22         return max;
    23         
    24     }

  • 相关阅读:
    Win10 WSL Ubuntu18.04 编译安装MySQL5.7
    PHP7 深入理解
    php session 测试
    nginx 匹配路由分发php和golang
    composer 库无法提交git
    Win10 1803安装Ubuntu1804子系统
    dhtmlxTreeGrid使用
    win7 64位系统下安装PL/SQL连接Oracle服务器的解决方法
    转载--eclipse快捷键
    JUnit4学习笔记2-Eclipse中使用JUint4进行单元测试
  • 原文地址:https://www.cnblogs.com/lolybj/p/8453964.html
Copyright © 2011-2022 走看看