for(char c:s)遍历字符串 增强型for循环
C++ for(char c:s)遍历字符串 增强型for循环_c++ for (char c : s)-CSDN博客
字符串使用前要进行扩容
reserve函数
【C++String类成员函数辨析】resize(),size(),capacity(),reserve()函数的解析与对比_c++ reserve函数-CSDN博客
a.size()
用来计算字符串的长度,末尾的\0不计算在内
交替合并字符串
class Solution {
public:string mergeAlternately(string word1, string word2) {int m=word1.size();int n = word2.size();string ans;int i=0;int j=0;ans.reserve(m+n);while(i<m||j<n){if(i<m){ans.push_back(word1[i]);++i;}if(j<n){ans.push_back(word2[j]);++j;}}return ans;}
};
找不同
class Solution {
public:char findTheDifference(string s, string t) {/*for(int i=0;i<s.size();i++)t[0]^=s[i];for(int i=1;i<t.size();i++)t[0]^=t[i];return t[0];}*/vector<int> cnt(26,0);for(char ch:s){cnt[ch-'a']++;}for(char ch:t){cnt[ch-'a']--;if(cnt[ch-'a']<0){ return ch;}}return ' ';}
};
异或运算的特性:
异或自己得0,任何数异或0得自己本身;
具有交换律、结合律,例如 1^2^3^4^2^3^1 = (1^1)^(2^2)^(3^3)^4 = 0^0^0^4 = 0^4 = 4;
总结:异或运算擅长找不同。
遍历两个字符串,时间复杂度O(m+n)
#include <iostream>
#include <string>
using namespace std; int main() { string date; cin >> date; // 假设输入的日期格式是 yyyy-mm-dd,我们需要提取出月份和日期 int month = stoi(date.substr(5, 2)); // 提取月份,从索引5开始,长度为2 int day = stoi(date.substr(8, 2)); // 提取日期,从索引8开始,长度为2 // 判断逻辑:如果月份小于10或者(月份等于10且日期小于等于29),则还可以训练 if (month < 10 || (month == 10 && day < 29)) { cout << "No. It's not too late."; } else { cout << "QAQ"; } return 0;
}