leecode_2

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

这个题目是为了获得字符串中没有重复子字符串的长度。

第一种方法,暴力搜索。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        for (int i = 0; i < n; i++)
            //注意这里j可以等于n,当等于n时,下面的allUnique方法里面的i的范围就必须为i<end,不能等于,不然就越界了。
            for (int j = i + 1; j <= n; j++)
                if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
        return ans;
    }
    public boolean allUnique(String s, int start, int end) {
           //将从start到end-1的字符放入到set中,set中是不能存在相同的字符的。
        Set<Character> set = new HashSet<>();
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) return false;
            set.add(ch);
        }
        return true;
    }
}

第二种方法。

public class Solution {
    public int lengthOfLongestSubstring(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]
            //当set中不存在要添加的当前字符时,就将字符放入到set中,并计算添加进set中的字符长度
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
           //当set中存在要添加的字符时,就将set中要添加的字符和其之前的字符全都移除。
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39912556/article/details/82820094
今日推荐