I have the following O(N) code submitted:
class Solution {
public int lengthOfLongestSubstring(String s) {
int currentLongest = 0, idx = 0;
if (s.length() <= 1){ return s.length(); }
for (int i=1; i<s.length(); i++){
String str = s.substring(idx, i); //substring up to current char (exclusive)
int strLen = str.length();
int idxOf = str.indexOf(s.charAt(i)); //check if current char is in the substring
if (idxOf != -1){ //if contains duplicate
if (strLen > currentLongest){
currentLongest = strLen; //replace if it is the longest substring seen
}
idx += idxOf+1; //move front pointer after idxOf.
}
if (i == s.length() -1){ // if last iteration, do final check inclusive of last char
strLen = s.substring(idx, i+1).length();
if (strLen > currentLongest){
currentLongest = strLen;
}
}
}
return currentLongest;
}
}
which passes all the test cases, however, I feel its kind of a hodge podge mix of hacks and work arounds (ie the s.length() < 1 part). Not only that, I m unsure if the substring() and indexOf() calls are causing the performance to be worse as follows.
Runtime: 11 ms, faster than 71.13% of Java online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 49.2 MB, less than 19.11% of Java online submissions for Longest Substring Without Repeating Characters.
Requirements:
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.