xxxxxxxxxx
/*
Javascript Solution - With Better Performance
Methods used in this algorithm are:
1. Two Pointer Technique
2. Sliding Window Technique
3. Hash Map
Time complexity: O(N)
Space complexity: O(N),
If the string does not contain repeated characters,
then the hash map will contain N characters.
*/
const s = "sdtvtsgh"
const lengthOfLongestSubstring = function(s) {
let max_length = 0
let map = {}
let l = 0
for (let r = 0; r < s.length; r++) {
if (map.hasOwnProperty(s[r])) {
const collision_index = map[s[r]]
if (collision_index >= l) {
l = collision_index + 1
}
delete map[s[collision_index]]
}
if (!map.hasOwnProperty(s[r])) {
map[s[r]] = r
}
if (max_length < (r + 1) - l) {
max_length = (r + 1) - l
}
console.log(map, ': (', r + 1, '-', l, ')')
}
return max_length
}
console.log(lengthOfLongestSubstring(s))
// [Log]:
{ s: 0 } : ( 1 - 0 )
{ s: 0, d: 1 } : ( 2 - 0 )
{ s: 0, d: 1, t: 2 } : ( 3 - 0 )
{ s: 0, d: 1, t: 2, v: 3 } : ( 4 - 0 )
{ s: 0, d: 1, v: 3, t: 4 } : ( 5 - 3 )
{ d: 1, v: 3, t: 4, s: 5 } : ( 6 - 3 )
{ d: 1, v: 3, t: 4, s: 5, g: 6 } : ( 7 - 3 )
{ d: 1, v: 3, t: 4, s: 5, g: 6, h: 7 } : ( 8 - 3 )
max_length = 5
xxxxxxxxxx
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if (!s.length) return 0
let left = 0, right = 0
let maxLength = -Infinity
const hashSet = {}
const len = s.length
while(right < len){
if (hashSet.hasOwnProperty(s[right])){
if (hashSet[s[right]] >= left){
left = hashSet[s[right]]+1
}
}
const lenn = right-left+1
maxLength = Math.max(lenn, maxLength)
hashSet[s[right]] = right
right++
}
return maxLength
};
xxxxxxxxxx
// JavaScript Solution - Credit to @albertchanged on LC
// Sliding window implementation
var lengthOfLongestSubstring = function(s) {
if (!s.length) return 0;
let left = 0, right = 0;
let maxLength = -Infinity;
const set = new Set();
while (right < s.length) {
// If s[right] has not been seen yet
if (!set.has(s[right])) {
// Add it to the set
set.add(s[right]);
// Increase size of window to right
right++;
// Update maxLength; set size represents length of unique substring
maxLength = Math.max(maxLength, set.size);
} else {
// We've seen s[right] so we need to shrink the window
// Delete s[left] from set
set.delete(s[left]);
// Shrink window from left
left++;
}
}
return maxLength;
}
xxxxxxxxxx
import java.io.*;
class GFG {
public static int longestUniqueSubsttr(String str)
{
String test = "";
// Result
int maxLength = -1;
// Return zero if string is empty
if (str.isEmpty()) {
return 0;
}
// Return one if string length is one
else if (str.length() == 1) {
return 1;
}
for (char c : str.toCharArray()) {
String current = String.valueOf(c);
// If string already contains the character
// Then substring after repeating character
if (test.contains(current)) {
test = test.substring(test.indexOf(current)
+ 1);
}
test = test + String.valueOf(c);
maxLength = Math.max(test.length(), maxLength);
}
return maxLength;
}
// Driver code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println("The length of the longest "
+ "non-repeating character "
+ "substring is " + len);
}
}
// This code is contributed by Alex Bennet
xxxxxxxxxx
class Solution {
public int lengthOfLongestSubstring(String s) {int max=0;
HashMap<Character,Integer>hm=new HashMap<>();
for(int i=0,j=0;i<s.length();i++){
if(hm.containsKey(s.charAt(i))){
j=Math.max(j,hm.get(s.charAt(i))+1);
}
hm.put(s.charAt(i),i);
max=Math.max(max,i-j+1);
}
return max;
}
}
xxxxxxxxxx
public class Solution
{
public int LengthOfLongestSubstring(string str)
{
var dict = new Dictionary<char, int>();
var max = 0;
int start = 0;
for (int i = 0; i < str.Length; i++)
{
var x = str[i];
if (!dict.ContainsKey(x))
{
dict.Add(x, 1);
}
else
{
dict[x] += 1;
while (start <= i && dict.ContainsKey(str[start]) && dict[x] > 1)
{
dict[str[start]]--;
if (dict[str[start]] == 0)
dict.Remove(str[start]);
start++;
}
}
max = Math.Max(max, i - start + 1);
}
return max;
}
}
xxxxxxxxxx
/*
Given a string s, find the length of the longest substring (A substring is
a contiguous non-empty sequence of characters within a string.)
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.
*/
const longestStr = s => {
if(s.length < 2) return s.length
let [left, right, partial, curIdx, finalLength] =
[0, s.length, new Set(), 0, -Infinity]
while (left < right) {
partial.add(s[left])
const curChar = s[left+1]
// Base case to exit loop early
if (finalLength > (right - curIdx)) break
if (partial.has(curChar)) {
curIdx += 1
left = curIdx
partial.size > finalLength ? finalLength = partial.size : null
partial.clear()
}else left++
left === right ? partial.size > finalLength ?
finalLength = partial.size : null : null
}
return finalLength
}
const s = "abcabcbb" // 3
const res = longestStr(s)
console.log(res)
/*
Time Complexity: O(n) (average case)
Space Complexity: O(n)
*/
// With love @kouqhar
xxxxxxxxxx
class Solution {
/**
* @param String $s
* @return Integer
*/
function lengthOfLongestSubstring($s) {
}
}
xxxxxxxxxx
One thing needs to be mentioned is that when asked to find maximum substring, we should update maximum after the inner while loop to guarantee that the substring is valid. On the other hand, when asked to find minimum substring, we should update minimum inside the inner while loop.
The code of solving Longest Substring with At Most Two Distinct Characters is below:
int lengthOfLongestSubstringTwoDistinct(string s) {
vector<int> map(128, 0);
int counter=0, begin=0, end=0, d=0;
while(end<s.size()){
if(map[s[end++]]++==0) counter++;
while(counter>2) if(map[s[begin++]]--==1) counter--;
d=max(d, end-begin);
}
return d;
}
The code of solving Longest Substring Without Repeating Characters is below:
Update 01.04.2016, thanks @weiyi3 for advise.
int lengthOfLongestSubstring(string s) {
vector<int> map(128,0);
int counter=0, begin=0, end=0, d=0;
while(end<s.size()){
if(map[s[end++]]++>0) counter++;
while(counter>0) if(map[s[begin++]]-->1) counter--;
d=max(d, end-begin); //while valid, update d
}
return d;
}
I think this post deserves some upvotes! : )