zoukankan      html  css  js  c++  java
  • LeetCode:3.Longest Substring Without Repeating Characters

    思路:看到题目首先想到最大字符串匹配KMP算法

     1 public static int lengthOfLongestSubstring(String s) {
     2         int maxLength = 0;
     3         StringBuilder sb = new StringBuilder(s);
     4         a:for(int i = 0;i<sb.length();i++){
     5             StringBuilder sb2 = new StringBuilder("");
     6             sb2.append(sb.substring(i,i+1));
     7             b:for(int j=i+1;j<sb.length();j++){
     8                 c:for(int k =0;k<sb2.length();k++){
     9                     if(!sb.substring(j,j+1).equals(sb2.substring(k,k+1))){
    10 
    11                     }else{
    12                         if(maxLength<j-i)
    13                             maxLength = j-i;
    14                         break b;
    15                     }
    16                     if(k == sb2.length())
    17                         sb2.append(sb.substring(j,j+1));
    18                 }
    19             }
    20         }
    21         return maxLength;
    22 }

    参考后代码

    public static int lengthOfLongestSubstring(String s) {
            int n = s.length(), ans = 0;
            Map<Character, Integer> map = new HashMap<>(); // current index of character
            // try to extend the range [i, j]
            for (int j = 0, i = 0; j < n; j++) {
                if (map.containsKey(s.charAt(j))){
                    i = Math.max(map.get(s.charAt(j)), i);
                }
                ans = Math.max(ans, j - i + 1);
                map.put(s.charAt(j), j + 1);
            }
            return ans;
        }
  • 相关阅读:
    桂林印象
    快变
    近期的事
    *C#中使用ref和out一点认识!*
    *在框架集页面放置TreeView控件时页面跳转的问题解决*
    *无法找到脚本库的问题*
    *Ajax.Net快速入门*
    *网页过期*
    *Prototype开发笔记*
    *正则表达式*
  • 原文地址:https://www.cnblogs.com/huiAlex/p/7978884.html
Copyright © 2011-2022 走看看