1768. Merge Strings Alternately - Easy

前往題目

想法

  • 雙指針直接輪流把string拼起來

思路

  1. 雙指針
  2. word1 word2交替拼接
  3. 最後檢查是否有剩餘字母
  4. 回傳結果

Code

class Solution {
    public String mergeAlternately(String word1, String word2) {
        StringBuilder res = new StringBuilder(); // 結果

        int word1Index = 0, word2Index = 0; // 雙指針

        // 直到有一個或兩個指針出界為止
        while (word1Index < word1.length() && word2Index < word2.length()) {
            res.append(word1.charAt(word1Index));
            res.append(word2.charAt(word2Index));
            ++word1Index; // 移動指針
            ++word2Index;
        }

        // 檢查有無剩餘字母,頂多只有word1或word2,不會兩個都有剩
        if (word1Index < word1.length()) {
            res.append(word1.substring(word1Index, word1.length()));
        } else if (word2Index < word2.length()) {
            res.append(word2.substring(word2Index, word2.length()));
        }

        return res.toString();

    }
}

1768. Merge Strings Alternately - Easy
https://f88083.github.io/2024/07/05/1768-Merge-Strings-Alternately/
作者
Simon Lai
發布於
2024年7月5日
許可協議