王柳 发表于 2025-1-22 14:13:31

2025年1月21日刷题记载

1.leetcode1768标题
链接:1768. 瓜代合并字符串 - 力扣(LeetCode)
https://i-blog.csdnimg.cn/direct/13bf21f613ca4c0f85a61c8859718d9c.png代码:
class Solution {
public:
    string mergeAlternately(string word1, string word2) {
      string word3;
      int a = word1.size(), b = word2.size();
      int i = 0, j = 0;
      while(i<a || j<b){
            if(i<a){
                word3+=word1;
                i++;
            }
            if(j<b){
                word3+=word2;
                j++;
            }
      }
      return word3;
    }
}; 履历:


[*] 原代码中直接使用 word3 = word1 和 word3 = word2,这种方式在 word3 未初始化大小时会导致未界说行为。应该使用word3+=word1.
2.力扣1071题
链接:1071. 字符串的最大公因子 - 力扣(LeetCode)
https://i-blog.csdnimg.cn/direct/d2c2a69abda94c4282d1bb9faa1733ef.png
class Solution {
public:
    string gcdOfStrings(string str1, string str2) {
      int a=str1.size(),b=str2.size();
      int gcd_len=gcd(a,b);
      string gcd_string=str1.substr(0,gcd_len);
      if(check(str1,gcd_string) && check(str2,gcd_string)){
            return gcd_string;
      }else{
            return "";
      }
    }
private:
    bool check(string &a,string &b){
      int len_a=a.size(),len_b=b.size();
      int time=len_a/len_b;
      string repeated_str=b;
      for(int i=1;i<time;i++){
            repeated_str+=b;
      }
      return repeated_str==a;
    }
};
学习到:


[*]string可以直接通过+=进行拼接。
[*]gcd函数的使用
[*]substr函数:str.substr(start,length)
3.力扣1431标题
1431. 拥有最多糖果的孩子 - 力扣(LeetCode)
class Solution {
public:
    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
      int max = *max_element(candies.begin(),candies.end());
      vector<bool> index;
      for(int i=0;i<candies.size();i++){
            if(candies+extraCandies>=max){
                index.push_back(true);
            }else{
                index.push_back(false);
            }
      }
      return index;
    }
};  学习:


[*]新建vector:直接vector <type> name;
[*]push_back()在vector的末了添加元素
[*]求解最大值:int max = *max_element(candies.begin(),candies.end());(加*是解迭代器)
4.力扣345题
class Solution {
public:
    string reverseVowels(string s) {
      int i = 0, j = s.size() - 1;// 双指针
      unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
      while (i < j) {
            // 移动左指针,直到找到元音
            while (i < j && vowels.find(s) == vowels.end()) {
                i++;
            }
            // 移动右指针,直到找到元音
            while (i < j && vowels.find(s) == vowels.end()) {
                j--;
            }
            // 交换两个元音字符
            if (i < j) {
                swap(s, s);
                i++;
                j--;
            }
      }
      return s;
    }
};

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 2025年1月21日刷题记载