第一题 交替合并字符串
题目描述:
给你两个字符串 word1
和 word2
。请你从 word1
开始,通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长,就将多出来的字母追加到合并后字符串的末尾。
返回 合并后的字符串 。
代码如下:
/**
* @param {string} word1
* @param {string} word2
* @return {string}
*/
// 先将字符串变成小写的——>判断字符串长度(需符合条件)
var mergeAlternately = function(word1, word2) {
const lowerCaseWord1 = word1.toLowerCase()
const lowerCaseWord2 = word2.toLowerCase()
if( !(lowerCaseWord1.length >= 1 && lowerCaseWord1.length <= 100 && lowerCaseWord2.length >= 1 && lowerCaseWord2.length <= 100) ) return
// 选取长度最小的值作为循环遍历的次数,确保交替操作不越界
const minLen = Math.min(lowerCaseWord1.length, lowerCaseWord2.length)
const result = []
for(let i = 0;i < minLen; i++){
// 使用push方法实现交替效果
result.push(lowerCaseWord1[i], lowerCaseWord2[i])
}
// 这里使用slice将最长的那个字符串剩余部分截取接在result后面
result.push(
lowerCaseWord1.length > lowerCaseWord2.length ? lowerCaseWord1.slice(minLen) : lowerCaseWord2.slice(minLen)
)
// 使用join方法将result变为字符串返回
return result.join('')
};
时间复杂度:O(min(lowerCaseWord1.length,lowerCaseWord2.length))
官方解题 使用的思路是双指针
代码 如下:
var mergeAlternately = function(word1, word2) {
const m = word1.length, n = word2.length;
let i = 0, j = 0;
const ans = [];
while (i < m || j < n) {
if (i < m) {
ans.push(word1[i]);
++i;
}
if (j < n) {
ans.push(word2[j]);
++j;
}
}
return ans.join('');
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/merge-strings-alternately/solutions/1913930/jiao-ti-he-bing-zi-fu-chuan-by-leetcode-ac4ih/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
第二题 找不同
问题描述:
给定两个字符串 s
和 t
,它们只包含小写字母。
字符串 t
由字符串 s
随机重排,然后在随机位置添加一个字母。
请找出在 t
中被添加的字母。
使用异域法 代码如下 :
/**
* @param {string} s
* @param {string} t
* @return {character}
*/
var findTheDifference = function(s, t) {
let xor = 0
// 遍历s和t的每个字符 获取字符的ASCII码
for (const c of s) xor ^= c.charCodeAt()
for (const c of t) xor ^= c.charCodeAt()
// 将 ASCII 码值转换为实际字符
return String.fromCharCode(xor)
};
时间复杂度:O(n) ,空间复杂度:O(1)
异或运算的特性:
异或运算(XOR,符号^) 有以下关键性质:
1.相同数异或为0:a ^ a = 0
2.任何数与0异或为自身:a ^ 0 =a
3.交换律和结合律
总结
今日先暂且到这,明天继续!!!!坚持就是胜利!!也希望如果有小伙伴看到,对互联网感兴趣的也一起加入学习中,通过编写博客来监督自己!一起加油!可以的!!!!