当前位置:   article > 正文

刷题日记 | 字符串扩容和增强型for循环

刷题日记 | 字符串扩容和增强型for循环

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不计算在内


交替合并字符串 
 

  1. class Solution {
  2. public:
  3. string mergeAlternately(string word1, string word2) {
  4. int m=word1.size();
  5. int n = word2.size();
  6. string ans;
  7. int i=0;
  8. int j=0;
  9. ans.reserve(m+n);
  10. while(i<m||j<n)
  11. {
  12. if(i<m)
  13. {
  14. ans.push_back(word1[i]);
  15. ++i;
  16. }
  17. if(j<n)
  18. {
  19. ans.push_back(word2[j]);
  20. ++j;
  21. }
  22. }
  23. return ans;
  24. }
  25. };

找不同

  1. class Solution {
  2. public:
  3. char findTheDifference(string s, string t) {
  4. /*for(int i=0;i<s.size();i++)
  5. t[0]^=s[i];
  6. for(int i=1;i<t.size();i++)
  7. t[0]^=t[i];
  8. return t[0];
  9. }*/
  10. vector<int> cnt(26,0);//创建1个容量为26的动态数组,初始值为0;
  11. for(char ch:s) //遍历string每一个元素
  12. {
  13. cnt[ch-'a']++;//s中存在的字母 对应的cnt值为1
  14. }
  15. for(char ch:t)
  16. {
  17. cnt[ch-'a']--;//t中存在且s中没有存在的字母 对应的cnt值为-1
  18. if(cnt[ch-'a']<0)
  19. { return ch;//该元素为s,t中不同的元素}
  20. }
  21. return ' ';
  22. }
  23. };

异或运算的特性:

异或自己得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)


 

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int main() {
  5. string date;
  6. cin >> date;
  7. // 假设输入的日期格式是 yyyy-mm-dd,我们需要提取出月份和日期
  8. int month = stoi(date.substr(5, 2)); // 提取月份,从索引5开始,长度为2
  9. int day = stoi(date.substr(8, 2)); // 提取日期,从索引8开始,长度为2
  10. // 判断逻辑:如果月份小于10或者(月份等于10且日期小于等于29),则还可以训练
  11. if (month < 10 || (month == 10 && day < 29)) {
  12. cout << "No. It's not too late.";
  13. } else {
  14. cout << "QAQ";
  15. }
  16. return 0;
  17. }

stoi函数作用是将 n 进制的字符串转化为十进制,使用时包含头文件string

C++常用函数--stoi函数用法总结-CSDN博客date.

date.substr(a,b) //从第a位开始,一共b个 

substr函数的使用-CSDN博客 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/161873
推荐阅读
相关标签
  

闽ICP备14008679号