LeetCode:3.无重复字符的最长字串(longest-substring-without-repeating-characters)
题解和思路
完整代码
import java.util.*;
/**
* 在这里给出对类 LC3LStrWithoutReChar 的描述。
*
* @作者(yequan17)
* @版本(2021.12.7)
*/
public class LC3LStrWithoutReChar
{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
System.out.println(lengthOfLongestSubstring(s));
sc.close();
}
public static int lengthOfLongestSubstring(String s) {
int length=0;
Map<Character,Integer> map=new HashMap<>();
for(int end=0,start=0;end<s.length();end++){
char c=s.charAt(end);
if(map.containsKey(c)){
start=Math.max(map.get(c)+1,start);
}
length=Math.max(end-start+1,length);
map.put(s.charAt(end),end);
}
return length;
}
}