题目如下:
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.
大致翻译:
给出一个字符串,求出没有重复字符的最长子串的长度。
例如:
给出"abcabcbb",答案是"abc"的长度为3.
给出"bbbbb",答案是"b"的长度为1.
给出"pwwkew",答案是"wke"的长度为3. 注意答案必须是一个子串,"pwke"是一个子序列但并不是子串.
本题重点在于不重复的子串,想到HashSet是不允许存储重复的数据的,所以解法就利用HashSet来实现。
【Java代码】
public class Solution { public int lengthOfLongestSubstring(String s) { //不重复子串的长度 int length = 0; //构造不重复的set表 Set<Character> set = new HashSet<Character>(); int i = 0, j = 0; for(i = 0; i < s.length(); i++){ set.clear();//清空set表 set.add(s.charAt(i));//加入开始字符 for(j = i + 1; j < s.length(); j++){ if(set.add(s.charAt(j)));//如果成功加入,证明没有重复,程序继续 else break;//如果没成功加入,则跳出 } if(j - i >= length) length = j - i;//计算长度并保留最长长度 } return length; } }
如果有任何问题,欢迎跟我联系:[email protected]
我的github地址:github.com/WXRain
时间: 2024-12-13 20:04:36