刷题总结#12

来源:互联网 发布:淘宝汽车座垫套 编辑:程序博客网 时间:2024/06/05 10:06

#424. Longest Repeating Character Replacement
好巧妙的一道题!
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Input:
s = “ABAB”, k = 2

Output:
4

Explanation:
Replace the two ‘A’s with two ‘B’s or vice versa.

难点在于不知道该选择替换哪个字母,而且也不容易用直接的贪心算法去做。
我们假设一个slide window去滑动,这个slide window就保存了最大的长度。初始化的长度一定为此时的maxcnt(某个字母)+k,如果下一个遇到的字母仍然是maxcnt那个字母,则相应的maxcnt+k会增长,那么start不动,则实现了slide window的增长。如果下一个遇到的字母不是maxcnt那个字母,那么此时maxcnt没有更新的话,则maxcnt+k会小于end-start+1,所以便把start+1,维持最大长度。也就是说,只有遇到能更新maxcnt的字母,才有可能更新最大的长度。
Since we are only interested in the longest valid substring, our sliding windows need not shrink, even if a window may cover an invalid substring. We either grow the window by appending one char on the right, or shift the whole window to the right by one. And we only grow the window when the count of the new char exceeds the historical max count (from a previous window that covers a valid substring).

That is, we do not need the accurate max count of the current window; we only care if the max count exceeds the historical max count; and that can only happen because of the new char.

int characterReplacement(string s, int k) {
vector < int > cnt(30,0);
int len=s.length();
int maxcnt=0,start=0,end=0;
for(end=0;end < len;end++)
{
maxcnt=max(maxcnt,++cnt[s[end]-‘A’]);
if(maxcnt+k<=end-start)
{
–cnt[s[start++]-‘A’];
}
}
return len-start;
}

#436. Find Right Interval
Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the “right” of i.

For any interval i, you need to store the minimum interval j’s index, which means that the interval j has the minimum start point to build the “right” relationship for interval i. If the interval j doesn’t exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.


vector<int> findRightInterval(vector<Interval>& intervals) {
map<int, int> hash;
vector<int> res;
int n = intervals.size();
for (int i = 0; i < n; ++i)
hash[intervals[i].start] = i;
for (auto in : intervals) {
auto itr = hash.lower_bound(in.end);
if (itr == hash.end()) res.push_back(-1);
else res.push_back(itr->second);
}
return res;
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置

0 0
原创粉丝点击