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;
        }
    };
     
  • 相关阅读:
    centos pptp客户端 连接服务端
    工控上常见的通讯接口与协议
    winform无边框窗体拖动
    Winform实现窗体渐变色
    Win10系统安装
    WIN 10 系统能正常使用WLAN,无法连接以太网
    C#DataGridView分页显示数据
    遍历枚举的值
    C#dataGridView添加自增列
    Winform实现打印功能
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224927.html
Copyright © 2011-2022 走看看