1. 程式人生 > >LeetCode 第 3 題(Longest Substring Without Repeating Characters)

LeetCode 第 3 題(Longest Substring Without Repeating Characters)

sts mod while find his 代碼 key 不存在 簡單

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

LeetCode 第 3 題(Longest Substring Without Repeating Characters)