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

leetcode : Longest Substring Without Repeating Characters 解题报告

时间:2017-01-31 10:33:20      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:hashset   注意   size   poi   logs   ash   bbb   tag   思路   

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.

Subscribe to see which companies asked this question

 

tag : two pointers     HashSet

思路:

(1)从第一个字符开始遍历,计算以每个字符开始的最长无重复子字符串。 

(2)每一计算的子串存在零时的HashSet里面。 注意HashSet这个数据结构, 增加元素是add()不是put().

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        int max = 0;
        
        for(int i = 0; i < s.length(); i++) {
            HashSet<Character> set = new HashSet<Character>();
            set.add(s.charAt(i));
            if(max >= s.length() - i) {
                    break;
                }
            
            for(int j = i + 1; j < s.length(); j++) {
                
                if(set.contains(s.charAt(j))) {
                    break;
                } else {
                    set.add(s.charAt(j));
                }
            }
            max = Math.max(max, set.size());
        }
        
        return max;
       
    }
}

 

leetcode : Longest Substring Without Repeating Characters 解题报告

标签:hashset   注意   size   poi   logs   ash   bbb   tag   思路   

原文地址:http://www.cnblogs.com/superzhaochao/p/6358611.html

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