LeetCode OJ(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.
思路:可以采用hash算法,字符的二进制值映射到一个locs[256]数组中,令其值为-1,在值不为-1的索引处也恰好存储该字符的索引。注意到,从第一个字符开始遍历,若遍历到有与第一个字符相同的字符,则之前的都不可能是满足要求的substring,将起始位置设为当前位置+1,代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int locs[256];
        memset(locs, -1, sizeof(locs));
        int start = -1, max = 0;//start为当前子串的开始位置-1
        for (int i = 0; i < s.size(); i++)
        {
            if (locs[s[i]] >start)
            {
                start = locs[s[i]];
            }

            if (i - start > max)
            {
                max = i - start;
            }

            locs[s[i]] = i;
        }
        return max;
    }
};

还有另一种写法,不使用locs[256]那么大的数组来存储各个字符的二进制码,转换成字符来写,不过解法还是一样的。这种解法对于除字母之外的测试用例通不过,原因就在于(-‘a’)操作。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int max = 0, start = 0;
        bool showed[26];
        int position[26];
        for (int i = 0; i < 26; i++) {
            showed[i] = false;
            position[i] = 0;
        }
        for (int i = 0; i<s.size(); i++)
        {
            if (showed[s[i] - 'a'])
            {
                start = position[s[i] - 'a'] + 1;
                showed[s[i] - 'a'] = true;
                position[s[i] - 'a'] = i;
            }
            else
            {
                position[s[i] - 'a'] = i;
                showed[s[i] - 'a'] = true;
                max = max > (i - start + 1) ? max : (i - start + 1);
            }

        }
        return max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值