You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*`s` consists of English letters, digits, symbols and spaces.
34
+
*`s` consists of English letters, digits, symbols and spaces.
35
+
36
+
To solve the Longest Substring Without Repeating Characters problem in Java using a `Solution` class, we'll follow these steps:
37
+
38
+
1. Define a `Solution` class with a method named `lengthOfLongestSubstring`.
39
+
2. Initialize variables to keep track of the starting index of the substring (`start`), the maximum length (`maxLen`), and a hashmap to store characters and their indices.
40
+
3. Iterate through the string `s`, and for each character:
41
+
- Check if the character exists in the hashmap and its index is greater than or equal to the `start` index.
42
+
- If found, update the `start` index to the index after the last occurrence of the character.
43
+
- Update the maximum length if necessary.
44
+
- Update the index of the current character in the hashmap.
45
+
4. Return the maximum length found.
46
+
5. Handle the edge case where the input string is empty.
47
+
48
+
Here's the implementation:
49
+
50
+
```java
51
+
importjava.util.HashMap;
52
+
53
+
publicclassSolution {
54
+
55
+
publicintlengthOfLongestSubstring(Strings) {
56
+
// Initialize variables
57
+
int start =0;
58
+
int maxLen =0;
59
+
HashMap<Character, Integer> map =newHashMap<>();
60
+
61
+
// Iterate through the string
62
+
for (int end =0; end < s.length(); end++) {
63
+
char ch = s.charAt(end);
64
+
// If the character exists in the hashmap and its index is greater than or equal to the start index
65
+
if (map.containsKey(ch) && map.get(ch) >= start) {
66
+
// Update the start index to the index after the last occurrence of the character
67
+
start = map.get(ch) +1;
68
+
}
69
+
// Update the maximum length if necessary
70
+
maxLen =Math.max(maxLen, end - start +1);
71
+
// Update the index of the current character in the hashmap
0 commit comments