• 【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;
        }
    };
     
  • 相关阅读:
    linux 遇到(vsftpd)—500 OOPS:chroot
    linux中配置JAVA环境
    win主机ping不通linux的IP
    java:递归算法
    MySQL数据库中字段类型为tinyint,读取出来为true/false的问题
    Mybaitis-generator生成数据对象和时间的优化
    IntelliJ IDEA 2017.1.6 x64 的破解
    在eclipse中maven构建Web项目,tomcat插件在maven中的运用
    Maven 的聚合
    理解面向对象
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224927.html
Copyright © 2020-2023  润新知