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

【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 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值