码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:3.Longest Substring Without Repeating Characters

时间:2017-12-04 21:23:31      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:ima   ++   bsp   技术分享   turn   eating   substring   log   without   

技术分享图片

思路:看到题目首先想到最大字符串匹配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;
    }

 

LeetCode:3.Longest Substring Without Repeating Characters

标签:ima   ++   bsp   技术分享   turn   eating   substring   log   without   

原文地址:http://www.cnblogs.com/ErMengNJUniverser/p/7978884.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!