likes
comments
collection
share

Java&C++题解与拓展——leetcode1768.交替合并字符串【么的新知识】

作者站长头像
站长
· 阅读数 10
每日一题做题记录,参考官方和三叶的题解

题目要求

Java&C++题解与拓展——leetcode1768.交替合并字符串【么的新知识】

Java&C++题解与拓展——leetcode1768.交替合并字符串【么的新知识】

思路:双指针

  • 两个指针分别指两个串往答案里放,同时判断端点

Java

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int n1 = word1.length(), n2 = word2.length();
        int i1 = 0, i2 = 0;
        StringBuilder res = new StringBuilder();
        while (i1 < n1 || i2 < n2) {
            if (i1 < n1)
                res.append(word1.charAt(i1++));
            if (i2 < n2)
                res.append(word2.charAt(i2++));
        }
        return res.toString();
    }
}
  • 时间复杂度:O(n+m)O(n+m)O(n+m)
  • 空间复杂度:O(n+m)O(n+m)O(n+m)

C++

class Solution {
public:
    string mergeAlternately(string word1, string word2) {
        int n1 = word1.size(), n2 = word2.size();
        int i1 = 0, i2 = 0;
        string res;
        res.reserve(n1 + n2);
        while (i1 < n1 || i2 < n2) {
            if (i1 < n1)
                res.push_back(word1[i1++]);
            if (i2 < n2)
                res.push_back(word2[i2++]);
        }
        return res;
    }
};
  • 时间复杂度:O(n+m)O(n+m)O(n+m)
  • 空间复杂度:O(n+m)O(n+m)O(n+m)

Rust

impl Solution {
    pub fn merge_alternately(word1: String, word2: String) -> String {
        let (n1, n2) = (word1.len(), word2.len());
        let (mut i1, mut i2) = (0, 0);
        let mut res = "".to_string();
        while i1 < n1 || i2 < n2 {
            if i1 < n1 {
                res.push(word1.chars().nth(i1).unwrap());
                i1 += 1;
            }
            if i2 < n2 {
                res.push(word2.chars().nth(i2).unwrap());
                i2 += 1;
            }
        }
        res
    }
}
  • 时间复杂度:O(n+m)O(n+m)O(n+m)
  • 空间复杂度:O(n+m)O(n+m)O(n+m)

总结

  • 简单模拟光速结束……
  • 但、前两天的博客还在草稿箱里……先放他吃个二斤灰再说
欢迎指正与讨论!