Review:
977. Squares of a Sorted Array
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int n = nums.size();
vector<int> res;
int left = 0, right = n-1;
while(left<=right){
if(abs(nums[left]) < abs(nums[right])){
res.push_back(nums[right]*nums[right]);
right--;
}else{
res.push_back(nums[left]*nums[left]);
left++;
}
}
reverse(res.begin(), res.end());
return res;
}
};
滑动窗口:
209. Minimum Size Subarray Sum
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, right = 0;
int sum = 0;
int minVal = INT_MAX;
while(right < nums.size()){
sum += nums[right];
right++;
while(sum >= target && left < right){
minVal = min(minVal, right-left);
sum -= nums[left];
left++;
}
}
return minVal == INT_MAX ? 0 : minVal;
}
};
3. Longest Substring Without Repeating Characters(*)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int left = 0, right = 0;
unordered_map<int, int> map;
int res = 0;
while(right < s.size()){
char ch = s[right];
map[ch]++;
right++;
while(map[ch] > 1){
map[s[left]] --;
left++;
}
res = max(res, right-left);
}
return res;
}
};
自己写出现的问题:
这里我有一个地方想错了,重复的两个未必是两端,这样的话,就要把重复之前的全部都删掉,所以缩小窗口的时候,不能是map[s[right]]-- (只删掉重复的,而是s[left], 这样就能把重复之前的数字全部都删掉)
New:
125. Valid Palindrome
class Solution {
public:
bool isPalindrome(string s) {
string convStr;
for(int i=0; i<s.size(); i++){
if(isalnum(s[i])){
convStr += tolower(s[i]);
}
}
int left = 0, right = convStr.size()-1;
while(left <= right){
if(convStr[left] != convStr[right])
return false;
left++;
right--;
}
return true;
}
};
两个函数
isalnum
tolower