码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring Without Repeating Characters

时间:2014-12-05 21:10:24      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

题目描述:

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.

  这道题目不难,我自己鼓捣了一会,就写出来了。可是上网一搜,发现不是最优的。题目的tag显示要使用哈希表,我不会。

下面贴出我自己写的代码(非原稿,根据solution2作了部分修改)

solution1:

int lengthOfLongestSubstring(string s) {
    int len = s.size();
    if(len < 2)
        return len;
    else
    {
        int max = 1;
        int start = 0;
        int end;
        int k;
        for (end = 1;end < len;++end)
        {
            for (k = start;k < end;++k)
            {
                if(s[end] == s[k])
                {
                    if((end - start) > max)
                        max = end - start;
                    start = k + 1;
                    break;
                }
            }
        }
        if((end - start) > max)
            max = end - start;
        return max;
    }
}

solution2:

 int lengthOfLongestSubstring(string s) {
     int len = s.size();
     if(len < 2)
         return len;
     else
     {
         int hash[256];
         for (int i = 0;i < 256;++i)
             hash[i] = -1;
         int max = 1;
         int start = 0;
         int end = 1;
         hash[s[0]] = 0;
         while (end < len)
         {
             if (hash[s[end]] >= start)
             {
                 if((end - start) > max)
                     max = end - start;
                 start = hash[s[end]] + 1;
             }
             hash[s[end]] = end;
             ++end;
         }
         if((end - start) > max)
             max = end - start;
         return max;
     }
 }

solution1是常规解法,solution2是优化算法。

solution2利用字符串中的字符和其对应的ascii码来建立哈希表,从而降低"在子串中查找重复字符"这一操作的复杂度。

详细解释请参考下文:http://blog.csdn.net/likecool21/article/details/10858799

Longest Substring Without Repeating Characters

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/gattaca/p/4147341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!