标签:https without ash 说明 uniq solution 题目 pre with
题目来源: https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/
问题描述: 计算一个字符串的最长子串的长度,子串不允许包含重复字符。
举例说明:
输入字符串 | 返回结果 | 解释 |
---|---|---|
abcabcbb | 3 | 最长子串是abc |
bbbbb | 1 | 最长子串是b |
pwwkew | 3 | 最长子串是wke |
解决方案
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++)
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) {
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;
}
}
标签:https without ash 说明 uniq solution 题目 pre with
原文地址:https://www.cnblogs.com/xiaoyangjia/p/11634018.html