From e5ec64c40ac4eaf5e3733de1f816cd926fb676e4 Mon Sep 17 00:00:00 2001 From: Li Miao Date: Fri, 20 Mar 2015 02:35:12 +0800 Subject: [PATCH] Longest Substring Without Repeating Characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 考虑非字母的字符 --- C++/chapGreedy.tex | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/chapGreedy.tex b/C++/chapGreedy.tex index 86b67e3a..b5543a2a 100644 --- a/C++/chapGreedy.tex +++ b/C++/chapGreedy.tex @@ -282,21 +282,22 @@ \subsubsection{代码} \begin{Code} // LeetCode, Longest Substring Without Repeating Characters // 时间复杂度O(n),空间复杂度O(1) +// 考虑非字母的情况 class Solution { public: int lengthOfLongestSubstring(string s) { - const int ASCII_MAX = 26; + const int ASCII_MAX = 255; int last[ASCII_MAX]; // 记录字符上次出现过的位置 int start = 0; // 记录当前子串的起始位置 fill(last, last + ASCII_MAX, -1); // 0也是有效位置,因此初始化为-1 int max_len = 0; for (int i = 0; i < s.size(); i++) { - if (last[s[i] - 'a'] >= start) { + if (last[s[i]] >= start) { max_len = max(i - start, max_len); - start = last[s[i] - 'a'] + 1; + start = last[s[i]] + 1; } - last[s[i] - 'a'] = i; + last[s[i]] = i; } return max((int)s.size() - start, max_len); // 别忘了最后一次,例如"abcd" }