LeetCode 第 3 题(Longest Substring Without Repeating Characters)

LeetCode 第 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.

求一个字符串的最长无重复子串。也是个比较简单的题目。涉及到的知识点主要是字符串操作和如何确定字符是否重复。遍历一个字符串可以用 iterator。判断一个字符是否出现过可以用集合(set)类型。
因此, 我在程序中设立了一个 std::set 型变量 dict。判断一个字符是否在 dict 中存在,用的是 count() 方法,返回 0 表示不存在这个字符。添加一个字符用的是 insert 方法,删除一个字符是 erase 方法。

另外一个要点是如何遍历这个字符串。我的程序中设计了头尾两个指针。先用头指针遍历字符串。中间碰到有重复字符了就移动尾指针,直到头尾指针之间没有重复字符为止。这样我的程序只需实时监控头尾指针之间的最大距离就行了。

下面是代码:

int lengthOfLongestSubstring(string s)
{
    string::const_iterator head = s.cbegin();
    string::const_iterator tail = s.cbegin();
    std::set<char> dict;
    int count, maxCount = 0;
    while( head != s.cend() )
    {
        if( dict.count(*head) == 0)
        {
            dict.insert(*head);
            count = dict.size();
            maxCount = (count > maxCount) ? count : maxCount;
        }
        else
        {
            while( *tail != *head )
            {
                dict.erase(*tail);
                ++tail;
            }
            ++tail;
        }
        ++head;
    }
    return maxCount;
}

这个代码虽然计算结果是正确的。但是运行速度略慢。要想提高运行速度,还是要在判别一个字符是否重复的算法上下功夫。因为常见的英文字符就那么几个,所以可以直接用查表法来处理。下面是改进后的代码。运行速度快了不少。

int lengthOfLongestSubstring(string s)
{
    string::const_iterator head = s.cbegin();
    string::const_iterator tail = s.cbegin();
    char dict[128];
    memset(dict, 0, 128);
    int count = 0, maxCount = 0;
    while( head != s.cend() )
    {
        if( dict[*head] == 0)
        {
            dict[*head] = 1;
            ++ count;
            maxCount = (count > maxCount) ? count : maxCount;
        }
        else
        {
            while( *tail != *head )
            {
                dict[*tail] = 0;
                -- count;
                ++tail;
            }
            ++tail;
        }
        ++head;
    }
    return maxCount;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值