LeetCode_3_LongestSubstringWithoutRepeatingCharacters(Java Code)

来源:互联网 发布:网络规划与设计题库 编辑:程序博客网 时间:2024/06/06 04:39

题目:找出给定字符串中所有无重复字符的子串的最大长度,例如:字符串”abcaccab”的最大无重复字符的子序列是”abc”,length=3。”bbbbb”的最大无重复字符的子序列是”b”,length=1。LeetCode原题

/** * 测试类*/public class TestSolution {    public static void main(String[] args) {        Solution sol = new Solution();        String s = "abcaccab";        System.out.println(sol.lengthOfLongestSubstring(s));    }}/** * 核心类   题目:LongestSubstringWithoutRepeatingCharacters * @author ChrisWang * @Date 2016年2月21日 上午9:46:11  * @Description 找出给定字符串中所有无重复字符的子串的最大长度 * @Example 字符串"abcaccab"的最大无重复字符的子序列是"abc", length=3; *          "bbbbb"的最大无重复字符的子序列是"b", length=1; * @Think 以字符串"abcaccab"为例: *          1, 前面三个字符没有重复的,所以前三次循环后的set为[a, b, c] *          2, 第四次循环时,begin指向了第四个字符a,此时和set中的第一个字符重复   *              此时end = 0; begin = 3; 此处记录max=3, *              然后删除第一个a以及其之前的所有字符,此时的set为[b, c, a] *          3, 以下以此类推 *         set集合就像是一个在字符串上移动的小窗口,窗口的大小可变,但窗口中不能有重复的字符串, *             每一次窗口的大小如果比max大,则替换max的值,这样保证max是最大的值 */class Solution {    public int lengthOfLongestSubstring(String s) {        if(s==null || s.length()==0) {            return 0;        }        HashSet<Character> set = new HashSet<Character>();        int max = 0;        int begin = 0;  // 窗口的右边界        int end = 0;    // 窗口的左边界        while(begin<s.length()) {            // set中包含该字符            if(set.contains(s.charAt(begin))) {                if(max<begin-end) {                    max = begin-end; // 记录较大的序列长度                }                while(s.charAt(end)!=s.charAt(begin)) {                    set.remove(s.charAt(end)); // 删除第一个重复字符之前的字符                    end++;                }                end++;            } else { // set中不包含则将字符放入到set中                set.add(s.charAt(begin));            }            begin++;        }        max = Math.max(max, begin-end);        return max;    }}
0 0