算法练习-LeetCode1768. Merge Strings Alternately

题目地址:LeetCode - The World's Leading Online Programming Learning Platform

类型:数组

难度:Esay

(1)自己最开始的想的解法(直接Loop交替循环):

时间复杂度:O(N)

空间复杂度:O(N)

class Solution {
    public String mergeAlternately(String word1, String word2) {
        
        char[] words1 = word1.toCharArray();
        char[] words2 = word2.toCharArray();
        int len1 = words1.length;
        int len2 = words2.length;
        StringBuilder builder = new StringBuilder();
        
        if(len1 > len2){
            for(int i = 0 ; i < len2; i++){
                builder.append(words1[i]);
                builder.append(words2[i]);
            }
            for(int j = len2; j < len1; j++){
                builder.append(words1[j]);
            }
            return builder.toString(); 
            
        }else{
            for(int i = 0 ; i < len1; i++){
                builder.append(words1[i]);
                builder.append(words2[i]);
            }
            for(int j = len1; j < len2; j++){
                builder.append(words2[j]);
            }
            return builder.toString(); 
        }
        

    }

}

(2)参考别人的算法再次解题:

class Solution {
    public String mergeAlternately(String word1, String word2) {
        
       StringBuilder builder = new StringBuilder();

        int i = 0; // an indicator
        int len1 = word1.length();
        int len2 = word2.length();

       while(i < len1 || i < len2){

           if(i < len1){
               builder.append(word1.charAt(i));
           }
           if(i < len2){
               builder.append(word2.charAt(i));
           }

            i++;
       }
        return builder.toString();
    }

}

解题思路:挺巧妙的用了一个indicator(i)和限制条件(i < len1)和(i < len2 ),就避免了如果转换为char数组后,会出现越界的问题。

你可能感兴趣的:(算法,leetcode,数据结构,java,数组)