• 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     }

  • 相关阅读:
    RabbitMq(四)远程过程调用RPC
    RabbitMq(三)交换机类型
    RabbitMq(二)工作队列
    java基础知识01--JAVA准备
    匿名子类
    网络之Socket详解
    网络之Socket、TCP/IP、Http关系分析
    Eclipse搭建springboot项目(九)常用Starter和整合模板引擎thymeleaf
    Vue学习——Router传参问题
    sql函数——find_in_set()
  • 原文地址:https://www.cnblogs.com/lolybj/p/8453964.html
Copyright © 2020-2023  润新知