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);//創建1個容量為26的動態數組,初始值為0;for(char ch:s) //遍歷string每一個元素{cnt[ch-'a']++;//s中存在的字母 對應的cnt值為1}for(char ch:t){cnt[ch-'a']--;//t中存在且s中沒有存在的字母 對應的cnt值為-1if(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
C++常用函數--stoi函數用法總結-CSDN博客date.
date.substr(a,b) //從第a位開始,一共b個?
substr函數的使用-CSDN博客?