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

原文地址:https://www.cnblogs.com/gavanwanggw/p/7226959.html