zoukankan      html  css  js  c++  java
  • LeetCode3:Longest Substring 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.

    解题思路:

    一开始,没看清题目要求,以为是去重,一提交出错才知不是。

    只要谈到去重或者无重复之类的词,就应该想到哈希表或bitmap。

    这里直接引用网上大牛的解题方法:http://blog.csdn.net/kenden23/article/details/16839757

    利用两指针i,j。i走在前,每次到哈希表中查找之前是否出现,没有则将对应位置置1,若出现过,说明开始下一个子串

    实现代码:

    #include <iostream>
    #include <string>
    #include <cstring>
    using namespace std;
    
    /**
    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.
    */
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            if(s.empty())
                return 0;
            int len = s.size();
            int bitmap[256] = {0};
            //memset(bitmap, 0, sizeof(int) * 26);
            int maxLen = 0;
            int j = 0;
            for(int i = 0; i < len; i++)
            {
                if(bitmap[s[i]] == 0)
                {
                    bitmap[s[i]] = 1;
                }
                else
                {
                    maxLen = max(maxLen, i-j);
                    while(s[i] != s[j])//对bitmap进行设置,将重复元素之前的所有元素对应的位置0,因为这些元素不参与下一次字符串 
                    {
                        bitmap[s[j]] = 0;
                        j++;
                        
                    }
                    j++;
                }        
            }
            maxLen = max(maxLen, len-j);//for循环退出是因为i =len,所以这里还要判断 
            return maxLen;
            
        }
    };
    
    int main(void)
    {
    
        string s("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco");
        Solution solution;
        int res = solution.lengthOfLongestSubstring(s);
        cout<<res<<endl;
        return 0;
    }
  • 相关阅读:
    Linux下编辑、编译、调试命令总结——gcc和gdb描述
    scanf函数读取缓冲区数据的问题
    Windows下设置Ubuntu引导项
    前端术语汇总笔记(会保持更新)
    实现动态加载一个 JavaScript 资源
    提取一个字符串中的数字,并将其转为数组
    CSS3图片倒影技术
    js函数聚合
    js继承函数封装
    联动菜单实现思路
  • 原文地址:https://www.cnblogs.com/mickole/p/3698956.html
Copyright © 2011-2022 走看看