NC402. 包含不超过两种字符的最长子串
描述
输入描述
仅一行,输入一个仅包含小写英文字母的字符串输出描述
输出最长子串的长度示例1
输入:
nowcoder
输出:
2
示例2
输入:
nooooow
输出:
6
C 解法, 执行用时: 4ms, 内存消耗: 408KB, 提交时间: 2022-07-30
#include <stdio.h> int main() { char s[100001] = ""; scanf("%s", s); int h = strlen(s); int H = 0; int v[26] = { 0 }, c = 0, a = 0, k = 0; for (int i = 0; i < h; i++) { k = s[i] - 'a'; if (v[k] == 0) { v[k] = 1; c++; if (c == 3) { if (i - a > H) { H = i - a; } while (c == 3) { k = s[a++] - 'a'; if (v[k] == 1) { v[k] = 0; c--; } else { v[k] -= 1; } } } } else { v[k] += 1; } } if (c <= 2) { if (h - a > H) { H = h - a; } } printf("%d", H); return 0; }
C 解法, 执行用时: 4ms, 内存消耗: 456KB, 提交时间: 2022-06-28
#include <stdio.h> int main() { char s[100001] = ""; scanf("%s", s); int sLen = strlen(s); int maxLen = 0; int hash[26] = { 0 }, chCount = 0, begin = 0, vKey = 0; for (int i = 0; i < sLen; i++) { vKey = s[i] - 'a'; if (hash[vKey] == 0) { hash[vKey] = 1; chCount++; if (chCount == 3) { if (i - begin > maxLen) { maxLen = i - begin; } while (chCount == 3) { vKey = s[begin++] - 'a'; if (hash[vKey] == 1) { hash[vKey] = 0; chCount--; } else { hash[vKey] -= 1; } } } } else { hash[vKey] += 1; } } if (chCount <= 2) { if (sLen - begin > maxLen) { maxLen = sLen - begin; } } printf("%d", maxLen); return 0; }
C 解法, 执行用时: 4ms, 内存消耗: 472KB, 提交时间: 2022-05-03
#include <stdio.h> //159. 至多包含两个不同字符的最长子串 int lengthOfLongestSubstringTwoDistinct(char* s) { int len = strlen(s); int maxLen = 0; int count = 0;//不同字符的个数 int hash[128] = {0}; int left = 0, right = 0; while (right < len) { hash[s[right]]++; if (hash[s[right]] == 1) { count++; } while (count > 2) { hash[s[left]]--; if (hash[s[left]] == 0) { count--; } left++; } maxLen = fmax(maxLen, right - left + 1); right++; } return maxLen; } int main() { int s[100000]; scanf("%s", &s); printf("%d", lengthOfLongestSubstringTwoDistinct(s)); return 0; }
C++ 解法, 执行用时: 6ms, 内存消耗: 556KB, 提交时间: 2022-07-29
#include<iostream> #include<string> #include<vector> using namespace std; int main() { string s; cin >> s; int L = 0, R = 0, c = 0, z = 0; vector<int> freq(26); while (R < s.size()) { if (freq[s[R] - 'a'] == 0) { c++; } freq[s[R] - 'a'] ++; R++; while (c > 2) { freq[s[L] - 'a'] --; if (freq[s[L] - 'a'] == 0) { c --; } L++; } z = max(z, R - L); } cout << z << endl; }
C++ 解法, 执行用时: 6ms, 内存消耗: 656KB, 提交时间: 2022-07-12
#include<iostream> #include<string> #include<vector> using namespace std; int main(){ string s; cin >> s; int l = 0, r = 0, count = 0, res = 0; vector<int> freq(26); while(r < s.size()){ if(freq[s[r] - 'a'] == 0){ count ++; } freq[s[r] - 'a'] ++; r ++; while(count > 2){ freq[s[l] - 'a'] --; if(freq[s[l] - 'a'] == 0){ count --; } l ++; } res = max(res, r - l); } // return res; cout << res << endl; }