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

本文介绍了C++中字符串操作,包括增强型for循环、使用reserve和resize()管理字符串容量、计算字符串长度、合并字符串的交替方式、findTheDifference函数利用异或运算查找不同字符,以及stoi和substr函数的应用实例。
摘要由CSDN通过智能技术生成

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值为-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

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

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

substr函数的使用-CSDN博客 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值