赞
踩
for(char c:s)遍历字符串 增强型for循环
字符串使用前要进行扩容
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);//创建1个容量为26的动态数组,初始值为0;
- for(char ch:s) //遍历string每一个元素
- {
- cnt[ch-'a']++;//s中存在的字母 对应的cnt值为1
- }
- for(char ch:t)
- {
- cnt[ch-'a']--;//t中存在且s中没有存在的字母 对应的cnt值为-1
- if(cnt[ch-'a']<0)
- { return ch;//该元素为s,t中不同的元素}
- }
- 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;
- }
stoi函数作用是将 n 进制的字符串转化为十进制,使用时包含头文件string
date.substr(a,b) //从第a位开始,一共b个
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。