題目
給定一個(gè)字符串。請(qǐng)你找出其中不含有重復(fù)字符的 最長(zhǎng)子串 的長(zhǎng)度。
-
示例
輸入 s="abcabcbb"
輸出 3
因?yàn)闊o(wú)重復(fù)字符的最長(zhǎng)子串是 "abc",所以其長(zhǎng)度為 3。
-
示例
輸入: s = "bbbbb"
輸出: 1
解釋: 因?yàn)闊o(wú)重復(fù)字符的最長(zhǎng)子串是 "b",所以其長(zhǎng)度為 1。 -
示例
輸入: s = "pwwkew"
輸出: 3
解釋: 因?yàn)闊o(wú)重復(fù)字符的最長(zhǎng)子串是 "wke",所以其長(zhǎng)度為 3。請(qǐng)注意,你的答案必須是 子串 的長(zhǎng)度,"pwke" 是一個(gè)子序列,不是子串。
題解

無(wú)重復(fù)字符串.jpg
private static int StringLength(String str) {
Set hasSet = new HashSet();
int nums = str.length();
int ans = 0;
for (int i = 0; i < nums; i++) {
int index = i;
while (index < nums && !hasSet.contains(str.charAt(index))) {
hasSet.add(str.charAt(index));
index++;
}
ans = Math.max(ans, index-i);
hasSet.clear();
}
return ans;
}