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     }

  • 相关阅读:
    第一章 教育观
    教资时间及考试分布情况
    第二章 信号量及条件变量(三)——> 重点
    Apache ftpServer 配置用户
    下载谷歌拼音输入法离线包
    springboot 启动脚本优化
    Json序列化和反序列化注意点-无参构造器
    Springboot2使用redis提示无法注入redisTemplate
    【转】iOS 保持界面流畅的技巧
    Java文件操作相关
  • 原文地址:https://www.cnblogs.com/lolybj/p/8453964.html
Copyright © 2011-2022 走看看