C++ code in 9 lines
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); }
return maxLen; }
O(n) time O(1) space solution using Kadane's algo in Java
public class Solution { public int lengthOfLongestSubstring(String s) {
int lastIndices[] = new int[256];
for(int i = 0; i<256; i++){ lastIndices[i] = -1; }
int maxLen = 0;
int curLen = 0;
int start = 0;
int bestStart = 0;
for(int i = 0; i<s.length(); i++){
char cur = s.charAt(i);
if(lastIndices[cur] < start){ lastIndices[cur] = i; curLen++; } else{
int lastIndex = lastIndices[cur]; start = lastIndex+1; curLen = i-start+1; lastIndices[cur] = i; }if(curLen > maxLen){ maxLen = curLen; bestStart = start; } } return maxLen; } }
Share my Java solution using HashSet
public int lengthOfLongestSubstring(String s) {
int i = 0, j = 0, max = 0; Set<Character> set = new HashSet<>();
while (j < s.length()) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++)); max = Math.max(max, set.size()); } else {
set.remove(s.charAt(i++)); } } return max; }