最长不重复字串code

#include <iostream>
using namespace std;
const int N = 10000 + 5;


int dp[N], pos[26];

string longestSubstr(string ss)
{
    if (ss.length() == 0) return "";
    for (int i = 0; i < 26; i++) pos[i] = -1;
    
    // dp
    dp[0] = 1;
    pos[ss[0] - 'a'] = 0;
    for (int i = 1; i < ss.length(); i++) {
        dp[i] = i - pos[ss[i] - 'a']; // check last postion
        if (dp[i] > dp[i - 1] + 1) dp[i] = dp[i - 1] + 1;
        
        pos[ss[i] - 'a'] = i;
    }
    
    
    // output ans
    int max = 1;
    int idx = 0;
    for (int i = 0; i < ss.length(); i++) {
        if (max < dp[i]) {
            max = dp[i];
            idx = i;
        }
    }
    
    return ss.substr(idx - max + 1, max);

}

int main()
{
    string ss;
    while (cin >> ss) {
        cout << longestSubstr(ss) << endl;
    }
    
    return 0;
}

/*
 由26 个小写字母组成的字符串str,在str 中查找最长不含相同字符的连续子串。如 abcacfrar,为acfr。
 */

 

posted on 2013-12-12 07:16  joy32812  阅读(225)  评论(0)    收藏  举报

导航