977. Squares of a Sorted Array
双指针
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int left = 0, right = nums.size()-1;
vector<int> res(nums.size(), 0);
int i= nums.size() - 1 ;
while(left <= right){
if(abs(nums[left]) > abs(nums[right])){
res[i] = nums[left] * nums[left];
left ++;
}else{
res[i] = nums[right] * nums[right];
right--;
}
i--;
}
return res;
}
};
注意一个问题出现的情况
在函数中该返回string的地方返回了int。尤其注意是不是return "0"写成了return 0
这道题需要给res设置初始值
344. Reverse String
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0, right = s.size() -1;
while(left < right){
swap(s[left],s[right]);
left++;
right--;
}
}
};
5. Longest Palindromic Substring
class Solution {
public:
string longestPalindrome(string s) {
string res = "";
for(int i=0; i<s.length(); i++){
string s1 = palin(s, i, i);
string s2 = palin(s, i, i+1);
res = s1.length() > res.length() ? s1 : res;
res = s2.length() > res.length() ? s2 : res;
}
return res;
}
string palin(string s,int l, int r){
while(l >=0 && r <s.size() && s[l] == s[r]){
l--;
r++;
}
return s.substr(l+1, r-l-1);
}
};
回文串问题:
1.需要从中间向两边
2.会有两种情况,奇数和偶数
209. Minimum Size Subarray Sum
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, right = 0;
int res = INT_MAX;
int windowSum = 0;
while(right < nums.size()){
windowSum += nums[right];
right ++;
while(windowSum >= target && left < right){
res = min(res, right-left);
windowSum -= nums[left];
left ++;
}
}
return res == INT_MAX ? 0 : res;
}
};
滑动窗口题
substr函数的形式为s.substr(pos, n)
3. Longest Substring Without Repeating Characters
滑动窗口
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> window;
int left = 0, right = 0;
int res = 0;
while(right < s.length()){
char ch = s[right];
window[ch] ++;
right ++;
while(window[ch] > 1 && left < right){
char d = s[left];
window[d] --;
left ++;
}
res = max(right-left, res);
}
return res;
}
};
tips:
1. unordered_map的一些用法
插入 insert
删除 erase
是否存在:count 只可以查找是否存在,存在1,不存在0;也可以用find
可以当作数组使用,如map[char]++
2.这里需要缩小完窗口在计算res
438. Find All Anagrams in a String
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> map1;
for(int i=0; i<p.length(); i++){
map1[p[i]]++;
}
unordered_map<char, int> window;
int left = 0, right = 0;
int valid = 0;
vector<int> res;
while(right < s.length()){
char ch = s[right];
right ++;
if(map1.count(ch)){
window[ch]++;
if(window[ch] == map1[ch]) valid++;
}
while(right-left >= p.length()){
if(valid == map1.size()){
res.push_back(left);
}
char e = s[left];
left++;
if (map1.count(e)) {
if (window[e] == map1[e])
valid--;
window[e]--;
}
}
}
return res;
}
};