Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = "" Output: 0
Solution:
Before jumping to solve the problem, Give few mins gap and think. How can you approach for the problem...
Steps:
1. Add every character to set (Ex: i = 0 ; j = 0)
2. Check if the character is existing in the set or not ( increment i and add the char to set)
3. If it exist then take the max size of set and clear the set and start from the next character again.
(if char exist then get max value of set and increment j and assign j to i and loop again)
import java.util.HashSet;
public class LongestSubstringWithoutRepeatChar {
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("abcabcabcd"));
}
public static int lengthOfLongestSubstring(String s) {
HashSet<Character> store = new HashSet<Character>();
int max = 0;
for (int i = 0, j = 0; i < s.length();) {
if (!store.contains(s.charAt(i))) {
store.add(s.charAt(i));
i++;
} else {
i = j++;
max = Math.max(max, store.size());
store.clear();
}
}
max = Math.max(max, store.size());
return max;
}
}
Thanks for reading :)
Whether this post is helpful?
Have something to add to this post? If you have any other quick thoughts/hints that you think people will find useful? Share it in the comments. feedback are welcome...
No comments:
Post a Comment