Given a string s of lower and upper case English letters.
A good string is a string which doesn’t have two adjacent characterss[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100
s contains only lower and upper case English letters.
Solution: Stack
Iterator over the string, compare current char with top of the stack, if they are a bad pair, pop the stack (remove both of them). Otherwise, push the current char onto the stack.
Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.
Find the kth positive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5
Output: 9
Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
Example 2:
Input: arr = [1,2,3,4], k = 2
Output: 6
Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
Solution 1: HashTable
Store all the elements into a hashtable, and check from 1 to max(arr).
Time complexity: O(max(arr)) ~ O(1000) Space complexity: O(n)
C++
1
2
3
4
5
6
7
8
9
10
11
12
// Author: Huahua
classSolution{
public:
intfindKthPositive(vector<int>& arr, int k) {
unordered_set<int> s(begin(arr), end(arr));
for(inti=1;i<=arr.back();++i){
if(!s.count(i))--k;
if(k==0)returni;
}
returnarr.back()+k;
}
};
Solution 2: Binary Search
We can find the smallest index l using binary search, s.t. arr[l] – l + 1 >= k which means we missed at least k numbers at index l. And the answer will be l + k.