Longest Substring Without Repeating Characters - LeetCode
C++ Code
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
vector<bool> isPresent(256, false);
int i=0, j=0;
int maxLength = 0;
while(j<n) {
if(!isPresent[(int) s[j]]) {
isPresent[(int) s[j]] = true;
maxLength = max(maxLength, j-i+1);
j++;
} else {
isPresent[(int) s[i]] = false;
i++;
}
}
return maxLength;
}
};
TypeScript Code
function lengthOfLongestSubstring(s: string): number {
const n: number = s.length;
let isPresent: Array<boolean> = new Array<boolean>(256).fill(false);
let i = 0, j = 0;
let maxLength = 0;
while(j<n) {
if(!isPresent[s.charCodeAt(j)]) {
isPresent[s.charCodeAt(j)] = true;
maxLength = Math.max(maxLength, j-i+1);
j++;
} else {
isPresent[s.charCodeAt(i)] = false;
i++;
}
}
return maxLength;
};
Go Code
func lengthOfLongestSubstring(s string) int {
n := len(s);
isPresent := make([]bool, 256);
i := 0;
j := 0;
maxLength := 0;
for j<n {
if !isPresent[int (s[j])] {
isPresent[int (s[j])] = true;
if maxLength < j-i+1 {
maxLength = j-i+1;
}
j++;
} else {
isPresent[int (s[i])] = false;
i++;
}
}
return maxLength;
}