8000 Longest Substring Without Repeating Characters by LiEmail · Pull Request #64 · soulmachine/leetcode · GitHub
[go: up one dir, main page]

Skip to content

Longest Substring Without Repeating Characters #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your a 8000 ccount

Merged
merged 1 commit into from
Jan 8, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions C++/chapGreedy.tex
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
0