leetcode题目3
题目说明:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
题目解析:从字符串中获取不含有重复字符的最长子串,常用的方法有暴力破解法、KMP算法。
我会的方法目前只有暴力破解法,KMP算法后面学会了再补充。。
暴力破解法的原理就是从第一个字符开始遍历,遇到重复的字符则获取当前子串长度,是否最大,如果是,更新最大值,,直到遍历到最后一个字符,就能获取到最大子串的长度。
KMP算法:期待后续补充。。
延伸:可以获取到相应最长子串的值。
public static int count(String str) {if (str == null || str.length() == 0) {return 0;}int max = 0, count = 0;Set<Character> nonRepeat;for (int i = 0; i < str.length(); i++) {nonRepeat = new HashSet<>();nonRepeat.add(str.charAt(i));count = 1;for (int j = i + 1; j < str.length(); j++) {if (nonRepeat.contains(str.charAt(j))) {if (nonRepeat.size() > max) {max = nonRepeat.size();}break;} else {nonRepeat.add(str.charAt(j));count++;}}}return max;}
鸡汤:顺其自然,人生会顺畅很多,豁达以对,世界会温柔很多。
code code code
文章转载自明日之X,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




