LeedCode无重复字符的最长子串
题目要求:
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
注意,你的答案必须是 子串 的长度
示例: 输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3
0 <= s.length <= 5 * 10^4
s 由英文字母、数字、符号和空格组成
这里需要注意的一点是 ,不需要把符号和空格去掉,符号和空格也算字符串的字符
接下来开始解题:
看到这道题目,刚开始稍微写了一下,也没仔细考虑怎么写,先一步步走。毕竟实在不行就跳出来,看看怎么写,大部分时候自己不会一看到题目或者问题就心中有数,除非你以前写过或者接触过,写完了发现有Bug,先看看我以前写:
public class NoReapte {
public static void main(String[] args) {
String s = "abcabcbb";
System.out.println(new Solution().lengthOfLongestSubstring(s));
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
//去掉字符串中的符号
String s1 = s.replaceAll("[^a-zA-Z]", "");
System.out.println(s1);
//要比较的话,用啥存
int length = s1.length();
int shortest = 0;
String using = "";
for (int i = 0; i < length; i++) {
if (using.contains(s1.charAt(i) + "")) {
if (shortest <= using.length()) {
shortest = using.length();
}
using = "";
if (select(s1, s1.charAt(i)) == 2) {
i = s1.indexOf(s1.charAt(i)) + 1;
}
if (select(s1, s1.charAt(i)) > 2) {
i = s1.indexOf(s1.charAt(i),i-shortest);
}
}
using = using + s1.charAt(i);
System.out.println(1);
System.out.println(using);
if (i == length - 1) {
if (shortest <= using.length()) {
shortest = using.length();
}
break;
}
}
return shortest;
}
//写一个方法统计字符串某个字符出现的次数
public int select(String str, char a) {
int count = 0;
char[] chars = str.toCharArray();
for (char i : chars) {
if (i == a) {
count++;
}
}
return count;
}
}
这段有Bug的代码我差不多相隔了俩个礼拜,终于有时间再看看
看啥呢,看得我自己都头大,刚从Hashmap的链表结构出来,那就直接用map来写这个吧,而且我感觉map来写比较方便。
import java.util.HashMap;
import java.util.Map;
/**
* @Author:Yun
* @Date:2022/01/19/11:25
* @Description:
**/
public class Reapte {
public static void main(String[] args) {
String s = "abc!ad";
System.out.println(new Solutions().lengthOfLongestSubstring(s));
}
}
class Solutions {
public int lengthOfLongestSubstring(String str) {
int length = str.length();
//打算用map来存最长的字符串,要注意这里的key类型得是Object,因为测试用例 由英文字母、数字、符号和空格组成
Map<Object, Integer> maps = new HashMap<>();
int longest = 0;
if (str.length() == 1) {
return 1;
}
if (str.length() >= 2) {
for (int i = 0; i < length; ) {
if (!maps.containsKey(str.charAt(i))) {
maps.put(str.charAt(i), i);
i++;
} else {
if (maps.size() > longest) {
longest = maps.size();
i = maps.get(str.charAt(i)) + 1;
maps.clear();
} else {
i = maps.get(str.charAt(i)) + 1;
maps.clear();
}
}
}
}
if (longest < maps.size()) {
longest = maps.size();
}
return longest;
}
}
这里为什么想到用map来存呢,主要是考虑到在字符串中碰到相同的字符,需要拿到相同字符前面一个的下个位置,作为再次的开始。
最后,测试的性能不是很可观,只能说解决了这个问题。在不断的学习过程中,自己慢慢发现每个人的认知是不一样的,不同的时间段也不一样,不必强求去看懂别人的代码,但是要去看,去了解去分析。在学习的过程中,我相信有那么一天,别人也会拿着你的代码,慢慢看。