My Solution to Longest Substring Without Repeating Characters

解法思想见原题:

http://www.leetcode.com/2011/05/longest-substring-without-repeating-characters.html

 

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

/* 
LeetCode: Longest Substring Without Repeating Characters
return value: length of longest substring
parameters: str - the whole string
*/
int LengthOfLongestSubstring(const string &str)
{
    int fullLen = str.length();

    int head = 0;
    int tail = 0;
    int currMaxLen = 0;
    int finalMaxLen = 0;
    bool label[256];
    for (int i = 0; i < 256; i++)
        label[i] = false;
    
    while (head < fullLen && tail < fullLen)
    {
        if (!label[str[head]]){
            label[str[head]] = true;
            head++;
            currMaxLen++;
        }
        else{
            if (currMaxLen > finalMaxLen)
                finalMaxLen = currMaxLen;        //先做记录工作
            for (int i = 0; i < 256; i++)        //再做清理工作
                label[i] = false;
            tail = head;
            currMaxLen = 0;
        }
    }
    return finalMaxLen;
}


int main()
{
    string a = "abcdeegh123eopq";
    cout<<LengthOfLongestSubstring(a)<<endl;
    return 0;
}

 

 

 

 

 

EOF

posted on 2012-12-08 23:17  kkmm  阅读(286)  评论(0编辑  收藏  举报