Skip to content

Commit 39c8f10

Browse files
committed
change logic
1 parent 61b4f8a commit 39c8f10

File tree

1 file changed

+33
-25
lines changed

1 file changed

+33
-25
lines changed

problem42/main.dart

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,39 @@
1-
2-
import 'dart:math';
3-
41
void main(List<String> args) {
5-
print(Solution().lengthOfLongestSubstring("pwwkew"));
6-
2+
print(Solution().lengthOfLongestSubstring("abba"));
73
}
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 = {};
813

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;
1418

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];
2022

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+
}
2927

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

Comments
 (0)