LeetCode No.3 Longest Substring 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.

====================================================================================================================================

这道题目属于中等题目,题目大意是:求给定字符串包含的没有重复字符的连续子字符串长度最大值

如果暴力搜索的话复杂度是O(N^2)甚至是O(N^3),我想这样可能都会超时(不然通过率怎么会这么低),所以这就需要一点处理字符的技巧了。

用一个长度为256的数组记录其对应ACSII的当前下标最大值,首先都初始化为-1,表示对应的下标还不存在。用i表示当前子字符串的起点下标,j表示当前字符串的终点下标,都初始化为0,下标从i到j表示当前没有重复字符的子字符串。

用j逐步往右扫,如果s[j]在i之后出现过时,即a[s[j]]>=i时,说明从i到j已经有字符跟s[j]重复了,这时候要先记录下当前最大长度为j-i,再实时更新ans,即ans = max ( ans , j - i ) ;因为下标从i到j表示当前没有重复字符的子字符串,所以i也要跟着变化,到了跟s[j]重复的那个字符的后面,也就是a[s[j]] + 1。最后记得更新a[s[j]] = j 和j++。大功告成!

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size() , i = 0 , j = 0 , a[256] , ans = 0 ;
        memset ( a , -1 , sizeof ( a ) ) ;
        while ( j < n )
        {
            if ( a[s[j]] >= i )
            {
                ans = max ( ans , j - i ) ;
                i = a[s[j]] + 1 ;
            }
            a[s[j]] = j ;
            j ++ ;
        }
        ans = max ( ans , j - i ) ;
        return ans ;
    }
};

举个例子说明一下:

比如给定的字符串s = "abcbdac"

刚开始a[0]~a[256]都是-1,i和j都是0,然后进入循环:

j = 0:  a['a'] = 0 , j = 1

j = 1:  a['b'] = 1 , j = 2

j = 2:  a['c'] = 2 , j = 3

j = 3:  因为a['b'] = 1 >= i = 0 , 判断成功,ans = max ( 0 , 3 - 0 ) = 3 , i = 1 + 1 = 2 ,a['b'] = 3 , j= 4

j = 4:  a['d'] = 4 , j = 5

j = 5:  a['a'] = 5 , j = 6

j = 6:  因为a['c'] = 2 >= i = 2 , 判断成功,ans = max ( 3 , 6 - 2 ) = 4 , i = 2 + 2 = 4 ,a['c'] = 6 , j= 7

退出循环,ans = max ( 4 , 7 - 4 ) = 4 

最大长度为4:即:"abcbdac"

如有错误,望告知改正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值