IT评测·应用市场-qidao123.com技术社区
标题:
2025年1月21日刷题记载
[打印本页]
作者:
王柳
时间:
2025-1-22 14:13
标题:
2025年1月21日刷题记载
1.leetcode1768标题
链接:1768. 瓜代合并字符串 - 力扣(LeetCode)
代码:
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];
i++;
}
if(j<b){
word3+=word2[j];
j++;
}
}
return word3;
}
};
复制代码
履历:
原代码中直接使用 word3[k] = word1
和 word3[k] = word2[j],这种方式在 word3 未初始化大小时会导致未界说行为。应该使用word3+=word1
.
2.力扣1071题
链接:1071. 字符串的最大公因子 - 力扣(LeetCode)
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[i]+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[i]) == vowels.end()) {
i++;
}
// 移动右指针,直到找到元音
while (i < j && vowels.find(s[j]) == vowels.end()) {
j--;
}
// 交换两个元音字符
if (i < j) {
swap(s[i], s[j]);
i++;
j--;
}
}
return s;
}
};
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/)
Powered by Discuz! X3.4