• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

Use HashSet

 1 class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s == null || s.length() < 0) return 0;
 4         int res = 0;
 5         int l = 0, r = 0;
 6         HashSet<Character> set = new HashSet<>();
 7         for (; r < s.length(); r ++) {
 8             if (set.contains(s.charAt(r))) {
 9                 while (l <= r && set.contains(s.charAt(r))) {
10                     set.remove(s.charAt(l));
11                     l ++;
12                 }
13             }
14             set.add(s.charAt(r));
15             res = Math.max(res, r - l + 1);
16         }
17         return res;
18     }
19 }

Use HashMap

 1    public int lengthOfLongestSubstring(String s) {
 2         if (s.length()==0) return 0;
 3         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 4         int max=0;
 5         for (int i=0, j=0; i<s.length(); ++i){
 6             if (map.containsKey(s.charAt(i))){
 7                 j = Math.max(j,map.get(s.charAt(i))+1);
 8             }
 9             map.put(s.charAt(i),i);
10             max = Math.max(max,i-j+1);
11         }
12         return max;
13     }

 



 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s==null || s.length()==0) return 0;
 4         HashSet<Character> set = new HashSet<>();;
 5         int l = 0, r = 0;
 6         int maxLen = 0;
 7         while (r < s.length()) {
 8             char cur = s.charAt(r);
 9             if (!set.contains(cur)) {
10                 set.add(cur);
11                 maxLen = Math.max(maxLen, r-l+1);
12                 r++;
13             }
14             else {
15                 set.remove(s.charAt(l));
16                 l++;
17             }
18         }
19         return maxLen;
20     }
21 }

 

 

posted @ 2014-06-11 03:24  neverlandly  阅读(357)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3