LeetCode之Longest Substring Without Repeating Characters

【题目描述】

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.

【解决思路】

方法可能比较笨,但是可用成功解决此问题,通过判断当前已存储的字符串中,是否已经有新的字符串了。如果存在则将其删除至oldchar位置,来保证当前字符串中没有重复字符串。

【代码实现】

private int length = 0;
    private StringBuilder sb = new StringBuilder();
    public int lengthOfLongestSubstring(String s)
    {
        int count = 0;
        for(char c : s.toCharArray())
        {
            if(sb.toString().contains(String.valueOf(c)))
            {
                //查找当前已经存在相同字符的位置,并将其之前的删除,仅保留后续字符,避免字符重复。
                int frist_index = sb.toString().indexOf(c) + 1;
                String str = sb.toString().substring(frist_index);
                sb =  new StringBuilder(str);
                sb.append(c);
                //由于已经更新了字符串信息,所以长度信息同步更新。
                count = count - frist_index + 1;
                continue;
            }
            sb.append(c);
            count ++;
            //保证当前length中存储的是最长字符串长度
            length = Math.max(length, count);
        }

return Math.max(length, count); }

【后续】

查看了leetcode上的相关解决思路,有个方法比较好,通过一个set来存储,避免了重复创建对象,这个方法还是比较好的,在此也贴下代码,以便后续学习用。

    public int lengthOfLongestSubstring2(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
原文地址:https://www.cnblogs.com/woniu4/p/8422997.html