码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 3. Longest Substring Without Repeating Characters

时间:2017-11-22 00:53:41      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:hand   with   was   special   tin   poi   highlight   ini   enc   

Problem reference: https://leetcode.com/problems/longest-substring-without-repeating-characters

// My solution:
// A simple dp, the key point is that the substring is serialy.

// Traverse every node and regard it as the end point,
// then we can figure out the state transition equation:
/*
    if (there was no duplicated letter before)
        answer[now] =  answer[now-1] + 1;
    else
        answer[now] = min(distance between the duplicated letters, answer[now-1] + 1)
*/

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.size() <= 1) return s.size();
        // Store the last position for a letter.
        std::map<char,int> last_char;
        std::map<char,int>::iterator it;
        
        // Store the optimum answer for every node.
        std::vector<int> rec;
        int ans = 0;
        for (int i=0;i<s.size();i++) {
            // Initialize value as result for current node.
            rec.push_back(1);
            it = last_char.find(s[i]);
            // Special handling of the initial character.
            if (i == 0) {
                last_char[s[i]] = i;
                continue;
            }
            if (it == last_char.end()) {
                rec[i] = rec[i-1] + 1;
            } else {
                rec[i]=min((i-(it->second)), rec[i-1] + 1);
            }
            last_char[s[i]] = i;
            ans = max(ans, rec[i]);
        }
        return ans;
    }
};

  

Leetcode 3. Longest Substring Without Repeating Characters

标签:hand   with   was   special   tin   poi   highlight   ini   enc   

原文地址:http://www.cnblogs.com/kkrisen/p/7876066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!