File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed
lengthOfLongestSubstringMethod1 Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ package LeetCode .String .lengthOfLongestSubstringMethod1 ;
2+
3+ public class Solution {
4+ public int lengthOfLongestSubstringMethod1 (String s ) {
5+ //max表示最长无重复子串的长度,t表示上一次无重复字符的下标,开始时从下标为0的字符开始
6+ int max = 0 ,t = 0 ;
7+ //str[]的下标为字符时表示该字符的ASCII值,标准ASCII字符总共的编码有128个
8+ int [] str = new int [128 ];
9+ //i表示正在访问的字符在串中的位置的下标(s.charAt(i)表示正在访问的字符)
10+ for (int i = 0 ;i < s .length ();i ++) {
11+ //如果不等于0表示前边已存在该字符,如过该字符的在串中的位置大于t表示该字符在正在判断的子串中
12+ if (str [s .charAt (i )] != 0 && str [s .charAt (i )] > t ){
13+ //更新max的值
14+ //i-t表示:当前无重复子串的长度(第i个下标表示的字符与第t个下标表示的字符相同)
15+ max = Math .max (max ,i -t );
16+ //更新t的值为str[s.charAt(i)]的值,即t的值为上一次无重复元素的位置+1
17+ t = str [s .charAt (i )];
18+ }else str [s .charAt (i )] = i +1 ;//上一次无重复字符在串中的位置
19+ }
20+ return Math .max (max ,s .length ()-t );
21+ }
22+ }
Original file line number Diff line number Diff line change 1+ package LeetCode .String .lengthOfLongestSubstringMethod1 ;
2+
3+ public class Test {
4+ public static void main (String [] args ) {
5+ Solution sol = new Solution ();
6+ System .out .println (sol .lengthOfLongestSubstringMethod1 ("abcabcbb" ));
7+ }
8+ }
You can’t perform that action at this time.
0 commit comments