Longest sub-string without repeating characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

 
C++:
01 int lengthOfLongestSubstring(string s) {
02     int n=s.size();
03     if(n==0)
04        return 0;
05     int* A=new int[n];
06     for(int i=0;i<n;i++)
07          A[i]=0;
08     for(int i=0;i<n;i++){
09         int cnt=0;
10         map <char,int> m;
11         for(int j=i;j<n;j++){
12             char c=s[j];
13             if(m.find(c)==m.end()){
14                  cnt++;
15                  m[c]=i;
16             }
17             else{
18                  A[i]=cnt;
19                  break;
20             }
21             A[i]=cnt;
22         }
23     }
24     int max=0;
25     for(int i=0;i<n;i++){
26         if(max<A[i])
27            max=A[i];
28         }
29     return max;
30 }
Advertisements
This entry was posted in Hashtable and Map, String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s