leetcode题目-最长子串
程序员文章站
2024-02-25 16:13:03
...
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*
解题代码:
public static boolean isRepeat(String str) {
HashSet<Character> hashSet = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
hashSet.add(str.charAt(i));
}
return hashSet.size() == str.length();
}
public static int lengthOfLongestSubstring(String s) {
if (s.length() == 1) {
return 1;
}
if (isRepeat(s)) {
return s.length();
}
if (lengthOfLongestSubstring(s.substring(0, s.length() - 1)) >= lengthOfLongestSubstring(s.substring(1, s.length()))) {
return lengthOfLongestSubstring(s.substring(0, s.length() - 1));
}
return lengthOfLongestSubstring(s.substring(1, s.length()));
}
平台运行没有通过,这个方法,运行时间过长,不建议递归实现,递归一般都比较耗时。
上一篇: 剑指offer28---数组中出现次数超过一半的数字
下一篇: C语言实现数组长度计算方法
推荐阅读
-
leetcode题目-最长子串
-
LeetCode3---无重复字符的最长子串
-
LeetCode算法题实现之JavaScript题三:无重复字符的最长子串。
-
【leetcode】3. 无重复字符的最长子串
-
leetcode算法题--无重复字符的最长子串
-
[leetcode题目解答]--(3)无重复字符的最长子串
-
leetcode的Hot100系列--3. 无重复字符的最长子串--滑动窗口
-
#leetcode刷题之路3-无重复字符的最长子串
-
括号相关题目 LeetCode 20 有效括号 LeetCode 32 最长有效括号子串
-
LeetCode - 无重复字符的最长子串【Java | LeetCode中级算法】