解法思想见原题:
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