58. 最后一个单词的长度
- 58. 最后一个单词的长度
- 思路:反向遍历
- 时间:O(n);空间:O(1)
class Solution {
public:int lengthOfLastWord(string s) {int id = s.size() - 1;while(s[id] == ' '){--id;}int ret = 0;while(id >= 0 && s[id] != ' '){ret++;id--;}return ret;}
};
1768. 交替合并字符串
- 1768. 交替合并字符串
- 思路:双指针,类似归并排序
- 时间:O(max(m, n));空间:O(1)
class Solution {
public:string mergeAlternately(string word1, string word2) {string ret;int p = 0, q = 0;int w1_size = word1.size(), w2_size = word2.size();while(p < w1_size && q < w2_size){ret += word1[p++];ret += word2[q++];}while(p < w1_size){ret += word1[p++];}while(q < w2_size){ret += word2[q++];}return ret;}
};