Given a string find the longest substring length of unique characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Approach
Java
import java.util.ArrayList;
import java.util.List;
public class LengthOfLongestSubstring {
public static void main(String[] args) {
String s = "abcabcbb";
int length = lengthOfLongestSubstring(s);
System.out.println(length);
}
private static int lengthOfLongestSubstring(String s) {
// base case
if (s.length() == 1)
return 1;
// create char list
List<Character> list = new ArrayList<>();
int length = 0;
// iterate till end of list
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// check element in list
// not found then add
if (!list.contains(c)) {
list.add(c);
} else {
// update size
if (list.size() > length)
length = list.size();
// find remove till index
int removeIndex = list.indexOf(c);
// remove index
list.remove(removeIndex);
// remove 0 to removeindex
for (int j = 0; j < removeIndex; j++) {
list.remove(0);
}
list.add(c);
}
}
// update size
if (list.size() > length)
return list.size();
return length;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the length of
//longest substring without
//repeating character
int lengthOfLongestSubstring(string s)
{
unordered_set<char> st;
int n=s.size();
int max1=0;
//iterate till the length
//of string
for(int i=0;i<n;i++)
{
int len=st.size();
st.insert(s[i]);
//if previous len is same
//as new length then the new character
//occurs prevoius
if(len==st.size())
{
//update the maximum
//length
if(len>max1)
max1=len;
//clear the set
st.clear();
//now insert into the set till we get
//the same character as current
//prevoiusly
for(int j=i-1;s[j]!=s[i];j--)
st.insert(s[j]);
//insert the current element
st.insert(s[i]);
}
else
{
//uodate the maximum length
if(st.size()>max1)
max1=st.size();
}
}
return max1;
}
int main()
{
string str="abcabcbb";
int length=lengthOfLongestSubstring(str);
cout<<length<<"\n";
return 0;
}
No comments:
Post a Comment