- The Longest Scene
A string, each character representing a scene. Between two identical characters is considered to be a continuous scene. For example: abcda, you can think of these five characters as the same scene. Or acafghbeb can think of two aca and beb scenes. If there is a coincidence between the scenes, then the scenes are combined. For example, abcab, where abca and bcab are coincident, then the five characters are considered to be the same scene. Give a string to find the longest scene.
Example
Given str = “abcda”, return 5.
Explanation:
The longest scene is “abcda”.
Given str = “abcab”, return 5.
Explanation:
The longest scene is “abcab”.
Notice
1 <= |str| <=1e5
str contains only lowercase letters
这题的思路就是对26个字母找出其出现最早和最晚的位置,然后对其排序(按出现最早的位置),然后合并Intervals,找出最大值。
注意:
- 对pair的排序默认按first来。
- 声明2维vector,第一维size=26,第2维不定
vector<vector<int>> vecs(26, vector<int>());
代码如下:
class Solution {
public:
/**
* @param str: The scene string
* @return: Return the length longest scene
*/
int getLongestScene(string &str) {
int strLen = str.size();
if (strLen == 0) return 0;
int result;
vector<vector<int>> vecs(26, vector<int>());
//pre-processing
for (int i = 0; i < strLen; ++i) {
int letterIndex = str[i] - 'a';
vecs[letterIndex].push_back(i);
}
//pair<int, int> wholeIntervals[26];
vector<pair<int, int>> wholeIntervals(26);
for (int i = 0; i < 26; ++i) {
if (vecs[i].size() > 0) {
wholeIntervals[i].first = vecs[i][0];
wholeIntervals[i].second = vecs[i][vecs[i].size() - 1];
}
}
sort(wholeIntervals.begin(), wholeIntervals.end());
int currIntervalSize = wholeIntervals[0].second - wholeIntervals[0].first;
int currIntervalBegPos = wholeIntervals[0].first;
int currIntervalEndPos = wholeIntervals[0].second;
int maxIntervalSize = wholeIntervals[0].second - wholeIntervals[0].first;
for (int i = 1; i < 26; ++i) {
if (wholeIntervals[i].first <= currIntervalEndPos) {
currIntervalSize = wholeIntervals[i].second - currIntervalBegPos;
currIntervalEndPos = wholeIntervals[i].second;
} else {
currIntervalSize = wholeIntervals[i].second - wholeIntervals[i].first;
currIntervalBegPos = wholeIntervals[i].first;
currIntervalEndPos = wholeIntervals[i].second;
}
maxIntervalSize = max(maxIntervalSize, currIntervalSize);
}
return maxIntervalSize + 1;
}
};