【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;
    }
};
 

 

posted @ 2019-01-05 16:07  wikiwen  阅读(156)  评论(0编辑  收藏  举报