前言:
经过前序的一系列数据结构和算法学习后,开始用leetCode热题练练手。
给定一个字符串 s
,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc"
,所以其长度为 3。
解题思路:
使用迭代变量字符串,效率还存在优化空间,下期分解。
1.本题使用128的数组存放出现字符的当前位置后一位的下标。
2.当前字符没有存放过则存放并计数。
3.当前字符出现过则计算最大值,并重置i的下标为之前出现重复字符的位置。
小知识点:128个字符ascii码表中最小的是" "空格符。
实现代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int length=s.length();
int res=0;
int tempRes=0;
int[] current=new int[128];
int i=0;
for(i=0;i<length;i++){
//int cur=i;
if(current[s.charAt(i)-' ']>0){
res=Math.max(res,tempRes);
//i置为当前下标,在i++后从之前出现重复的下一位置开始迭代
i=current[s.charAt(i)-' ']-1;
current=new int[128];
tempRes=0;
}else{
//为避免放入0下标,放入下一位下标
current[s.charAt(i)-' ']=i+1;
tempRes+=1;
}
}
res=Math.max(res,tempRes);
return res;
}
}
QA1: