zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】字符串题15:48 最长不含重复字符的子字符串(3. Longest Substring Without Repeating Characters)

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    3. Longest Substrleftng Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.
    Examples:
    Given "abcabcbb", the answer is "abc", which the length is 3.
    Given "bbbbb", the answer is "b", with the length of 1.
    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke"is a subsequence and not a substring.
     
     
    //找字符串中的最长无重复字符的子串
    /*
    方法:Sliding Window
    本质是枚举法
    O(n)
    */
    #include <unordered_set>
    #include <algorithm>
    class Solution
    {
    public:
        int lengthOfLongestSubstring(string s)
        {     
            unordered_set<char> set//用hash表存滑动窗中的数,方便查找是否有重复的数(用vector应该也可以,只不过hash表如果查找得到元素时效率高一点)
            int left = 0,right = 0; //双指针,指向子串区间的左右两端点
            int max_length = 0;
           
            while(right < s.size())
            {
                if(set.find(s[right]) == set.end())//如果不是重复字符,插入字符,更新最大长度
                {
                    set.insert(s[right++]); //插入右边元素,右指针加一
                    max_length = max(max_length, int(set.size())); //由于max函数只能对同类型的进行比较,这里强制转换
                }
                else//如果为重复字符,则移除区间首字符,直到set中不再含此字符为止(会多次判断,多次执行移除操作) 
                {
                    set.erase(s[left++]); //移除左边元素,左指针加一
                }
            }
            return max_length;
        }
    };
     
  • 相关阅读:
    慕课网 -- 性能优化之PHP优化总结笔记
    安装memcached服务 和 php 安装memcache扩展
    配置 host only 后 nat不能上网了
    linux svn soeasy
    wamp ssl配置https
    wamp 配置多站点访问
    安装wamp 缺少msvcr100.dll
    vagrant 相关记录
    复制mysql数据库的步骤
    php 的两个扩展 memcache 和 memcachd
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224927.html
Copyright © 2011-2022 走看看