首页 > 其他 > 详细

[leetcode] Longest Substring Without Repeating Characters

时间:2014-06-27 12:48:28      阅读:358      评论:0      收藏:0      [点我收藏+]

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

 

思路:利用一个exist数组保存字符是否出现(假设char set是ascii),从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计(如下图),同时注意exist数组的同步更新。

bubuko.com,布布扣

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int res = 1;
        boolean[] exist = new boolean[256];
        int start = 0;

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (exist[ch]) {
                res = Math.max(res, i - start);
                for (int k = start; k < i; k++) {
                    if (s.charAt(k) == ch) {
                        start = k + 1;
                        break;
                    }
                    exist[s.charAt(k)] = false;
                }
            } else
                exist[ch] = true;
        }
        res = Math.max(res, s.length() - start);
        return res;

    }

    public static void main(String[] args) {
        System.out.println(new Solution().lengthOfLongestSubstring("abcabcbb"));
        System.out.println(new Solution().lengthOfLongestSubstring("bbbbb"));
        System.out.println(new Solution()
                .lengthOfLongestSubstring("fpdcztbudxfipowpnamsrfgexjlbjrfoglthewbhtiriznzmolehqnlpwxrfowwwjrd"));

    }
}

 

 

 

参考:

http://blog.csdn.net/likecool21/article/details/10858799

http://www.programcreek.com/2013/02/leetcode-longest-substring-without-repeating-characters-java/

 

 

[leetcode] Longest Substring Without Repeating Characters,布布扣,bubuko.com

[leetcode] Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/jdflyfly/p/3810665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!