class Solution {
public:
// 方法一:直接合并后排序
void merge1(vector<int>& nums1, int m, vector<int>& nums2, int n){
for(int i=0;i<n;i++) nums1[m+i]=nums2[i];
// just std template, can try heap sort on hand.
std::sort(nums1.begin(), nums1.end());
}
// 方法二:双指针
void merge2(vector<int>& nums1, int m, vector<int>& nums2, int n){
vector<int> nums3;
int p0=0, p1=0;
while(p0 < m && p1 < n){
if(nums1[p0] < nums2[p1]){
nums3.push_back(nums1[p0]);
p0++;
}
else if(nums1[p0] > nums2[p1]){
nums3.push_back(nums2[p1]);
p1++;
}
else{
nums3.push_back(nums1[p0]);
nums3.push_back(nums2[p1]);
p0++;
p1++;
}
}
if(p0 >= m){
for(int i=p1;i<n;i++) nums3.push_back(nums2[i]);
}
else if(p1 >= n){
for(int i=p0;i<m;i++) nums3.push_back(nums1[i]);
}
nums1 = nums3;
}
// 方法三:逆向双指针
void merge3(vector<int>& nums1, int m, vector<int>& nums2, int n){
int p0 = m-1, p1=n-1, count=0;
while(p0 >=0 && p1 >= 0){
if(nums1[p0] > nums2[p1]){
nums1[m+n-1-count]=nums1[p0];
p0--;
count++;
}
else if(nums1[p0] < nums2[p1]){
nums1[m+n-1-count]=nums2[p1];
p1--;
count++;
}
else{
nums1[m+n-1-count]=nums1[p0];
p0--;
count++;
nums1[m+n-1-count]=nums2[p1];
p1--;
count++;
}
}
if(p0<0){
for(int i=p1;i>=0;i--){
nums1[m+n-1-count]=nums2[p1];
p1--;
count++;
}
}
else if(p1<0){
for(int i=p0;i>=0;i--){
nums1[m+n-1-count]=nums1[p0];
p0--;
count++;
}
}
}
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
merge3(nums1, m, nums2, n);
}
};
class Solution {
public:
// O(n^2),简单操作
int on2RemovEle(vector<int>& nums, int val){
int count = nums.size();
for(int i=nums.size()-1;i>=0;i--){
if(nums[i] == val){
nums.erase(nums.begin() + i);
count--;
}
}
return count;
}
// O(n),双指针
int onRemoveEle(vector<int>& nums, int val){
int p0=nums.size()-1, p1=0;
while(p0>=p1){
if(val==nums[p1]&&nums[p0]!=val){
nums[p1]=nums[p0];
p0--;
}
if(val==nums[p1]&&nums[p0]==val){
p0--;
p1--;
}
p1++;
}
for(int i=nums.size()-1;i>p0;i--){
nums.erase(nums.begin()+i);
}
return p0+1;
}
int removeElement(vector<int>& nums, int val) {
return onRemoveEle(nums, val);
}
};
class Solution {
public:
// 双指针
int removeDuplicates(vector<int>& nums) {
int index=0, slow=0, fast=0;
while(fast < nums.size()){
if(nums[slow]==nums[fast]) fast++;
else if(nums[slow]!=nums[fast]){
nums[index+1]=nums[fast];
index++;
slow=fast;
}
}
return index+1;
}
};
class Solution {
public:
// Boyer-Moore 投票算法,求众数
int majorityElementBM(vector<int>& nums) {
int count=0, candidateIndex=-1;
for(int i=0;i<nums.size();i++){
if(count==0){
candidateIndex=i;
count++;
}
else{
if(nums[candidateIndex]==nums[i]) count++;
else count--;
}
}
return nums[candidateIndex];
}
int majorityElement(vector<int>& nums) {
return majorityElementBM(nums);
}
};
class Solution {
public:
// 后面数和前面数字的最大差距
int maxProfit(vector<int>& prices) {
if(prices.size() == 0) return 0;
int minPrice=prices[0], maxProfit=0;
for(auto price: prices){
if(price-minPrice>maxProfit) maxProfit=price-minPrice;
if(price<minPrice) minPrice=price;
}
return maxProfit;
}
};
class Solution {
public:
// 末尾遍历
int lengthOfLastWord(string s) {
int len=0;
bool flag=false;
for(int i=s.size()-1; i>=0;i--){
if(s[i]==' ' && !flag) continue;
else if(s[i]==' ' && flag) break;
else if(s[i] != ' '){
flag=true;
len++;
}
}
return len;
}
};
class Solution {
public:
// 反转数字比较,可能溢出,所以直接int64
bool isPalindrome(int64_t x) {
if(x<0) return false;
int64_t reversi=0;
int64_t cmp=x;
while(x > 0){
reversi = reversi*10 + x%10;
x/=10;
}
return cmp==reversi;
}
};
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
digits[digits.size()-1]++;
for(int i=digits.size()-1;i>0;i--){
if(digits[i]==10){
digits[i-1]++;
digits[i]=0;
}
}
if(digits[0]==10){
digits[0]=0;
digits.insert(digits.begin(), 1);
}
return digits;
}
};
class Solution {
public:
// 相当于查找一个数的平方是x,二分查找
int mySqrt(int64_t x) {
if(x==1) return 1;
int64_t low=0, high=x,mid=(low+high)/2;
while(low < high){
mid=(low+high)/2;
if(mid*mid>x) high=mid;
else if(mid*mid<x) low=mid;
else{
low=mid;
break;
}
if(low+1==high) break;
}
return low;
}
};
class Solution {
public:
// 二分查找
int searchInsert(vector<int>& nums, int target) {
int low=0, high=nums.size()-1, mid=(low+high)/2;
while(low < high){
if(target < nums[mid]) high=mid-1;
else if(target > nums[mid]) low=mid+1;
else return mid;
mid=(low+high)/2;
}
if(nums[low] >= target) return low;
return mid+1;
}
};
验证回文串
class Solution {
public:
bool isAlphaNumber(char c){
if((c<='z' && c>='a')||(c<='Z'&&c>='A') || (c<='9'&&c>='0')) return true;
return false;
}
char cap2Not(char c){
if(c<='Z' && c>='A') return char(c+32);
return c;
}
bool isPalindrome(string s) {
int low=0, high=s.size()-1;
while(low <= high){
if(!isAlphaNumber(s[low])) low++;
else if(!isAlphaNumber(s[high])) high--;
else{
if(cap2Not(s[low]) != cap2Not(s[high])) return false;
low++;
high--;
}
}
return true;
}
};
class Solution {
public:
bool isSubsequence(string s, string t) {
int count=0;
for(int i=0;i<t.size();i++){
if(t[i]==s[count]){
count++;
}
}
if(count==s.size()) return true;
return false;
}
};
class Solution {
public:
bool isMate(char c1, char c2){
if((c1=='(' && c2==')')||(c1=='['&&c2==']')||(c1=='{'&&c2=='}')) return true;
return false;
}
bool isValid(string s) {
std::stack<char> stack;
for(auto c: s){
if(c=='('||c=='['||c=='{'){
stack.push(c);
}
else{
if(stack.empty()) return false;
if(!isMate(stack.top(), c)) return false;
stack.pop();
}
}
if(!stack.empty()) return false;
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode *slow=head, *fast=head->next;
while(fast){
if(fast == slow) return true;
if(!fast->next) return false;
slow=slow->next;
fast=fast->next->next;
}
return false;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode *p1=list1, *p2=list2;
ListNode *head, *rear;
head=new ListNode();
rear=head;
while(p1 && p2){
if(p1->val<p2->val){
rear->next=p1;
rear=rear->next;
p1=p1->next;
}
else if(p1->val > p2->val){
rear->next=p2;
rear=rear->next;
p2=p2->next;
}
else{
rear->next=p1;
rear=rear->next;
p1=p1->next;
rear->next=p2;
rear=rear->next;
p2=p2->next;
}
}
if(!p1){
rear->next=p2;
}
else{
rear->next=p1;
}
rear = head->next;
delete(head);
return rear;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int recursion(TreeNode* root){
if(!root) return 0;
int left = recursion(root->left)+1;
int right = recursion(root->right)+1;
return max(left, right);
}
int ergodic4Layer(TreeNode* root){
if(!root) return 0;
int layerNodeNum=0, index, height=0;
TreeNode* front;
std::queue<TreeNode*> q;
q.push(root);
layerNodeNum++;
while(!q.empty()){
index=layerNodeNum;
layerNodeNum=0;
height++;
for(int i=0;i<index;i++){
front=q.front();
q.pop();
if(front->left){
layerNodeNum++;
q.push(front->left);
}
if(front->right){
layerNodeNum++;
q.push(front->right);
}
}
}
return height;
}
int maxDepth(TreeNode* root) {
return ergodic4Layer(root);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool recursion(TreeNode* p, TreeNode* q){
if(!p && q) return false;
if(p && !q) return false;
if(!p && !q) return true;
if(p->val != q->val) return false;
return recursion(p->left, q->left) && recursion(p->right, q->right);
}
bool node4Layer(TreeNode* p, TreeNode* q){
if(!p && q) return false;
if(p && !q) return false;
if(!p && !q) return true;
std::queue<TreeNode*> queue1, queue2;
TreeNode* p1=p, *p2=q;
queue1.push(p1);
queue2.push(p2);
while(!queue1.empty() && !queue2.empty()){
p1=queue1.front();
p2=queue2.front();
queue1.pop();
queue2.pop();
if(p1->val != p2->val) return false;
if(p1->left && !p2->left) return false;
if(!p1->left && p2->left) return false;
if(p1->right && !p2->right) return false;
if(!p1->right && p2->right) return false;
if(p1->left && p2->left){
queue1.push(p1->left);
queue2.push(p2->left);
}
if(p1->right && p2->right){
queue1.push(p1->right);
queue2.push(p2->right);
}
}
return true;
}
bool isSameTree(TreeNode* p, TreeNode* q) {
return node4Layer(p, q);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* recursion(TreeNode* root){
if(!root || (!root->left && !root->right)) return root;
TreeNode* temp=root->right;
root->right=recursion(root->left);
root->left=recursion(temp);
return root;
}
TreeNode* node4Layer(TreeNode* root){
if(!root || (!root->left && !root->right)) return root;
std::queue<TreeNode*> q;
TreeNode* p, *tmp;
q.push(root);
while(!q.empty()){
p=q.front();
q.pop();
tmp=p->left;
p->left=p->right;
p->right=tmp;
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
return root;
}
TreeNode* invertTree(TreeNode* root) {
return node4Layer(root);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool recursionHelper(TreeNode* p, TreeNode* q){
if(!p && !q) return true;
if((!p && q) || (!q && p)) return false;
if(p->val != q->val) return false;
return recursionHelper(p->left, q->right) && recursionHelper(p->right, q->left);
}
bool recursion(TreeNode* root){
if(!root || (!root->left && !root->right)) return true;
if((!root->left && root->right) || (root->left && !root->right)) return false;
return recursionHelper(root->left, root->right);
}
bool node4Layer(TreeNode* root){
if(!root || (!root->left && !root->right)) return true;
if((!root->left && root->right) || (root->left && !root->right)) return false;
std::queue<TreeNode*> q1, q2;
TreeNode* left=root->left, *right=root->right;
q1.push(left);
q2.push(right);
while(!q1.empty() && !q2.empty()){
left=q1.front();
right=q2.front();
q1.pop();
q2.pop();
if(left->val != right->val) return false;
if((left->left && !right->right) || !left->left && right->right) return false;
if((left->right && !right->left) || !left->right && right->left) return false;
if(left->left && right->right) {
q1.push(left->left);
q2.push(right->right);
}
if(left->right && right->left){
q1.push(left->right);
q2.push(right->left);
}
}
return true;
}
bool isSymmetric(TreeNode* root) {
return node4Layer(root);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool recursion(TreeNode* root, int targetSum){
if(!root) return false;
targetSum -= root->val;
if(!root->left && !root->right && targetSum==0) return true;
return recursion(root->left, targetSum) || recursion(root->right, targetSum);
}
bool node4Layer(TreeNode* root, int targetSum){
if(!root) return false;
std::queue<TreeNode*> q;
std::queue<int> helper;
TreeNode* p;
int target;
q.push(root);
helper.push(targetSum);
while(!q.empty()){
p = q.front();
target = helper.front();
q.pop();
helper.pop();
if(target - p->val ==0 && !p->left && !p->right) return true;
if(p->left){
q.push(p->left);
helper.push(target - p->val);
}
if(p->right){
q.push(p->right);
helper.push(target - p->val);
}
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
return node4Layer(root, targetSum);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void recursion(TreeNode* root, int depth, vector<int> &layerNum,vector<double> &v){
if(!root) return;
v[depth]+=root->val;
layerNum[depth]++;
if(root->left) recursion(root->left, depth+1, layerNum, v);
if(root->right) recursion(root->right, depth+1, layerNum, v);
}
int getDepth(TreeNode* root){
if(!root) return 0;
int left = getDepth(root->left);
int right = getDepth(root->right);
return left > right? (left+1): (right+1);
}
vector<double> averageOfLevelsWithRecursion(TreeNode* root){
vector<int> layerNum;
vector<double> v;
int depth = getDepth(root);
for(int i=0;i<depth;i++){
layerNum.push_back(0);
v.push_back(0.0);
}
recursion(root, 0, layerNum, v);
for(int i=0;i<depth;i++){
v[i] /= layerNum[i];
}
return v;
}
vector<double> layer(TreeNode* root){
std::queue<TreeNode*> q;
vector<double> v;
TreeNode* temp;
q.push(root);
int layerNum=1;
double sumval=0;
while(!q.empty()){
int nextLayerNum=0;
for(int i=0;i<layerNum;i++){
temp=q.front();
q.pop();
if(temp->left){
q.push(temp->left);
nextLayerNum++;
}
if(temp->right){
q.push(temp->right);
nextLayerNum++;
}
sumval+=temp->val;
}
v.push_back(sumval/layerNum);
layerNum=nextLayerNum;
nextLayerNum=0;
sumval=0;
}
return v;
}
vector<double> averageOfLevels(TreeNode* root) {
return layer(root);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void order(TreeNode* root, int &pre, int &min){
if(root->left) order(root->left, pre, min);
if(!root) return;
if(min > root->val-pre) min=root->val-pre;
pre = root->val;
if(root->right) order(root->right, pre, min);
}
int getMinimumDifference(TreeNode* root) {
int min=10000;
int pre=-10000;
order(root, pre, min);
return min;
}
};
KMP算法
class Solution {
public:
// hash
bool canConstruct(string ransomNote, string magazine) {
if(magazine.size() < ransomNote.size()) return false;
int frep[26] = {0};
for(auto c: magazine) frep[c-'a']++;
for(auto c: ransomNote) frep[c-'a']--;
for(auto i: frep) if(i < 0) return false;
return true;
}
};
class Solution {
public:
// hash双射
bool isIsomorphic(string s, string t) {
if(s.size() != t.size()) return false;
if(s.size()==1 && t.size()==1) return true;
size_t s2t[128], t2s[128];
for(size_t i=0;i<128;i++){
s2t[i]=-1;
t2s[i]=-1;
}
for(int i=0;i<s.size();i++){
if(s2t[s[i]]!=-1 && s2t[s[i]]!=t[i] || t2s[t[i]]!=-1 && t2s[t[i]]!=s[i]) return false;
s2t[s[i]]=t[i];
t2s[t[i]]=s[i];
}
return true;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// 分治,左右两边
TreeNode* helper(vector<int>& nums, int left, int right){
if(left>right) return nullptr;
int mid = (left + right)/2;
TreeNode *root = new TreeNode();
root->val = nums[mid];
root->left = helper(nums, left, mid-1);
root->right = helper(nums, mid+1, right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums, 0, nums.size()-1);
}
};
class Solution {
public:
// x & (x-1) can remove the last one
int hammingWeight(uint32_t n) {
size_t count=0;
while(n){
count++;
n &= (n-1);
}
return count;
}
};
class Solution {
public:
int bitwise(vector<int>& nums){
int single=0;
for(auto num: nums) single^=num;
return single;
}
int hash(vector<int>& nums){
std::unordered_set<int> hash;
for(auto num: nums){
if(hash.find(num) != hash.end()) hash.erase(num);
else hash.insert(num);
}
return *(hash.begin());
}
int singleNumber(vector<int>& nums) {
return hash(nums);
}
};
class Solution {
public:
// hash
bool containsNearbyDuplicate(vector<int>& nums, int k) {
std::unordered_map<int, int> hash;
for(int i=0;i<nums.size();i++){
auto check = hash.find(nums[i]);
if(check != hash.end() && abs(i - check->second) <= k) return true;
else if(check != hash.end() && abs(i - check->second) > k) check->second = i;
else hash[nums[i]]=i;
}
return false;
}
};
class Solution {
public:
// double point
vector<string> summaryRanges(vector<int>& nums) {
if(nums.size()==0) return {};
if(nums.size()==1) return {std::to_string(nums[0])};
vector<string> returnStr;
size_t start=0, end=0;
for(int i=1;i<nums.size();i++){
if(abs(nums[i] - 1 != nums[i-1])){
end = i-1;
if(start==end){
returnStr.push_back(std::to_string(nums[start]));
}
else{
returnStr.push_back(std::to_string(nums[start])+ "->" + std::to_string(nums[end]));
}
start = i;
}
}
if(start == nums.size()-1) returnStr.push_back(std::to_string(nums[start]));
else returnStr.push_back(std::to_string(nums[start])+ "->" + std::to_string(nums[nums.size()-1]));
return returnStr;
}
};
// method of slip array.just using F(n) = F(n-1) + F(n-2).
int slipArray(int n){
if(n==1) return 1;
if(n==2) return 2;
// store history(the way of last three climbStairs.)
int array[3] = {1, 2};
for(int i=2; i<n;i++){
array[i%3] = array[(i-1)%3] + array[(i-2)%3];
}
return array[(n-1)%3];
}
vector<vector<int64_t>> mul(vector<vector<int64_t>> &a, vector<vector<int64_t>> &b) {
vector<vector<int64_t>> c(2, vector<int64_t>(2));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
return c;
}
// faster power
vector<vector<int64_t>> fastPower(vector<vector<int64_t>> a, int n) {
vector<vector<int64_t>> ret = {{1, 0}, {0, 1}};
while (n > 0) {
if ((n & 1) == 1) {
ret = mul(ret, a);
}
n >>= 1;
a = mul(a, a);
}
return ret;
}
// array calculation.
int arrayCalculation(int n){
std::vector<std::vector<int64_t>> result = {{1, 1}, {1, 0}};
return fastPower(result, n)[0][0];
}
// general term formula:using F(n) = F(n-1) + F(n-2), solve F(n).
// solve characteristic equation.x^2=x+1 --> x1=(1+5^0.5)/2 x2=(1-5^0.5)/2
// f(n)=c1x1^n+c2x2^n -->c1=1/5^0.5 c2=-1/5^0.5
int generalTermFormula(int n){
if(n==1) return 1;
return (1/pow(5, 0.5)) * pow((1+pow(5, 0.5))/2, n+1) + (-1/pow(5, 0.5)) * pow(((1-pow(5, 0.5))/2), n+1);
}
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
class Solution {
public:
// just like linklist's next point.
int getNextNumber(int n){
int number = 0;
while(n > 0){
number += ((n%10)*(n%10));
n /= 10;
}
return number;
}
// linklist method.
bool isHappyWith2Point(int n){
int slow=n, fast=getNextNumber(n);
// check circle.
while(true){
// must check if happyNumber or not first.
if(fast==1) return true;
if(fast==slow) return false;
slow = getNextNumber(slow);
fast = getNextNumber(fast);
fast = getNextNumber(fast);
}
// no way.
return false;
}
// hash
bool isHappyWithHash(int n){
std::unordered_set<int> hash;
while(n!=1){
if(hash.find(n) != hash.end()){
return false;
}
hash.insert(n);
n=getNextNumber(n);
}
return true;
}
bool isHappy(int n) {
return isHappyWithHash(n);
}
};
class Solution {
public:
// just for not using bitwise.
string addNotBitwise(string a, string b){
string result;
// check if overflow.
bool flag=false;
int i, j;
for(i=a.size()-1, j=b.size()-1;i>=0&&j>=0;i--,j--){
if(a[i] == '1' && b[j] == '1'){
if(flag){
result.push_back('1');
}
else{
result.push_back('0');
}
flag=true;
}
else if((a[i] == '0' && b[j] == '1') || (a[i] == '1' && b[j] == '0')){
if(flag){
result.push_back('0');
}
else{
result.push_back('1');
}
}
// 0 0
else{
if(flag){
result.push_back('1');
}
else{
result.push_back('0');
}
flag = false;
}
}
if(i<0 && j >= 0){
for(;j>=0;j--){
if(b[j]=='1'){
if(flag){
result.push_back('0');
}
else{
result.push_back('1');
}
}
else{
if(flag){
result.push_back('1');
}
else{
result.push_back('0');
}
flag=false;
}
}
}
else if(i>=0 && j<0){
for(;i>=0;i--){
if(a[i]=='1'){
if(flag){
result.push_back('0');
}
else{
result.push_back('1');
}
}
else{
if(flag){
result.push_back('1');
}
else{
result.push_back('0');
}
flag=false;
}
}
}
if(i < 0 && j < 0){
if(flag) result.push_back('1');
}
reverse(result.begin(), result.end());
return result;
}
string addBinary(string a, string b) {
return addNotBitwise(a, b);
}
};
class Solution {
public:
int romanToInt(string s) {
std::map<char, int> charMap = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
int number=0;
int sLen=s.size();
if(sLen==1) return charMap[s[0]];
number+=charMap[s[sLen-1]];
for(int i=sLen-2;i>=0;i--){
if(charMap[s[i]]<charMap[s[i+1]]) number-=charMap[s[i]];
else number+=charMap[s[i]];
}
return number;
}
};
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
bool sameFlag;
int i;
for(i=0;i<strs[0].size();i++){
sameFlag=true;
for(int j=0;j<strs.size();j++){
if(strs[j][i]!=strs[0][i]){
sameFlag=false;
break;
}
}
if(sameFlag==false) break;
}
return strs[0].substr(0, i);
}
};
class Solution {
public:
// string split.
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
size_t start = 0;
size_t end = str.find(delimiter);
while (end != std::string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
end = str.find(delimiter, start);
}
tokens.push_back(str.substr(start));
return tokens;
}
// hash
bool wordPattern(string pattern, string s) {
std::vector<std::string> str=split(s, ' ');
if(pattern.size()!=str.size()) return false;
std::unordered_map<char, string> p2s;
std::unordered_map<string, char> s2p;
for(int i=0;i<pattern.size();i++){
auto p2sFind = p2s.find(pattern[i]);
if(p2sFind !=p2s.end() && p2sFind->second!=str[i]) return false;
else if(p2sFind ==p2s.end()) p2s[pattern[i]]=str[i];
auto s2pFind = s2p.find(str[i]);
if(s2pFind !=s2p.end() && s2pFind->second!=pattern[i]) return false;
else if(s2pFind ==s2p.end()) s2p[str[i]]=pattern[i];
}
return true;
}
};
// reverse for every point.
uint32_t reverseBits4EveryPoint(uint32_t n){
uint32_t reverse=0;
for(int i=0;i<32;i++){
// get point i
uint32_t pointI = n & 1;
// make point i be last point
n >>= 1;
// reverse
pointI <<= (31-i);
// point i into reversed point 31-i
reverse |= pointI;
}
return reverse;
}
uint32_t reverseBits4EverySlice(uint32_t n){
// 01010101010101010101010101010101
// 00110011001100110011001100110011
// 00001111000011110000111100001111
// 00000000111111110000000011111111
// 00000000000000001111111111111111
const uint32_t maskLeftHalf[5] = {0x55555555, 0x33333333, 0x0f0f0f0f, 0x00ff00ff, 0x0000ffff};
// 10101010101010101010101010101010
// 11001100110011001100110011001100
// 11110000111100001111000011110000
// 11111111000000001111111100000000
// 11111111111111110000000000000000
const uint32_t maskRightHalf[5] = {0xaaaaaaaa, 0xcccccccc, 0xf0f0f0f0, 0xff00ff00, 0xffff0000};
for(int i=0;i<5;i++){
int moveBits = 1<<i;
// left swap.
uint32_t left = n >> moveBits;
// right swap
uint32_t right = n << moveBits;
// mask left half
left &= maskLeftHalf[i];
// mask right half
right &= maskRightHalf[i];
// left and right merge.
n = left | right;
}
return n;
}
// search for every node.
void node4EveryNode(TreeNode* root, int &count){
if(!root) return;
count++;
node4EveryNode(root->left, count);
node4EveryNode(root->right, count);
}
// get complete bit tree's depth.
int depth(TreeNode* root){
int depth=0;
while(root){
root = root->left;
depth++;
}
return depth;
}
// search for full bit tree.
int node4SearchFullBitTree(TreeNode* root){
if(!root) return 0;
int leftDepth = depth(root->left);
int rightDepth = depth(root->right);
if(leftDepth==rightDepth){
// 2^leftDepth
int leftCount = 1<<leftDepth;
return node4SearchFullBitTree(root->right) + leftCount;
}
// just left sub tree depth > right sub tree depth.
// 2^rightDepth
int rightCount = 1<<rightDepth;
return node4SearchFullBitTree(root->left) + rightCount;
}
KMP算法视频讲解
class Solution {
public:
// Function to get next array for KMP algorithm.
vector<int> getNextArray(string needle) {
// Initialize next array with size of needle
vector<int> nextArray(needle.size(), 0);
int prefixLen = 0;
for (int index = 1; index < needle.size(); index++) {
// Update prefixLen until a match is found or prefixLen becomes 0
while (prefixLen > 0 && needle[prefixLen] != needle[index]) {
prefixLen = nextArray[prefixLen - 1];
}
// If a match is found, increment prefixLen
if (needle[prefixLen] == needle[index]) {
prefixLen++;
}
// Update nextArray at current index with prefixLen
nextArray[index] = prefixLen;
}
// Return the next array
return nextArray;
}
// Function to perform string matching using KMP algorithm.
int strStr(string haystack, string needle) {
// Return 0 if needle is empty (edge case)
if (needle.empty()) return 0;
// Generate next array using needle
vector<int> nextArray = getNextArray(needle);
int i = 0, j = 0;
while (i < haystack.size()) {
if (haystack[i] == needle[j]) {
// Increment i and j if characters match
i++;
j++;
// If all characters in needle are matched, return starting index
if (j == needle.size()) {
return i - j; // Return the starting position of the match
}
} else {
// If characters don't match, update j using next array
if (j == 0) {
i++;
} else {
j = nextArray[j - 1];
}
}
}
// Return -1 if no match found
return -1;
}
};