1
-
2
- import 'dart:math' ;
3
-
4
1
void main (List <String > args) {
5
- print (Solution ().lengthOfLongestSubstring ("pwwkew" ));
6
-
2
+ print (Solution ().lengthOfLongestSubstring ("abba" ));
7
3
}
4
+ class Solution {
5
+ int lengthOfLongestSubstring (String s) {
6
+ if (s.isEmpty) {
7
+ print ("Input string is empty." );
8
+ return 0 ;
9
+ }
10
+
11
+ // Create a map to store the index of each character in the string
12
+ Map <String , int > charIndexMap = {};
8
13
9
- class Solution {
10
- int lengthOfLongestSubstring (String s) {
11
- var l = 0 ;
12
- var visit = < String > {};
13
- var res = 0 ;
14
+ // Initialize variables to keep track of the start and end of the current substring
15
+ int start = 0 ;
16
+ int maxLength = 0 ;
17
+ int maxStart = 0 ;
14
18
15
- for (var r = 0 ; r < s.length; r++ ){
16
- while (visit.contains (s[r])){
17
- visit.remove (s[l]);
18
- l += 1 ;
19
- }
19
+ // Iterate through the string
20
+ for (int end = 0 ; end < s.length; end++ ) {
21
+ String currentChar = s[end];
20
22
21
- visit.add (s[r]);
22
- print ("res = ${res }" );
23
- res = max (res, r - l + 1 );
24
- print ("l = ${l }" );
25
- print ("r = ${r }" );
26
- print ("res = ${res }" );
27
- }
28
- return res;
23
+ // If the current character is already in the substring, update the start index
24
+ if (charIndexMap.containsKey (currentChar) && charIndexMap[currentChar]! >= start) {
25
+ start = charIndexMap[currentChar]! + 1 ;
26
+ }
29
27
30
- }
31
- }
28
+ // Update the index of the current character
29
+ charIndexMap[currentChar] = end;
30
+
31
+ // Update the maximum length and starting index if the current substring is longer
32
+ if (maxLength < (end - start + 1 )) {
33
+ maxLength = end - start + 1 ;
34
+ maxStart = start;
35
+ }
36
+ }
37
+ return "${s .substring (maxStart , maxStart + maxLength )}" .length;
38
+ }
39
+ }
0 commit comments