Merging Strings Alternately – A Secure and Tested Approach

Merging Strings Alternately – A Secure and Tested Approach


What Change Would I Like My Blog to Bring to the World?

Through my blog, I aim to promote secure and efficient coding practices. By sharing well-tested solutions and clear explanations, I hope to help other developers enhance their skills and write better high-quality code.


Problem Description

Today, we’ll tackle the “Merge Strings Alternately” problem from LeetCode, classified as medium difficulty. The task is to merge two strings by alternating their characters. If one string is longer, its remaining characters should be appended to the merged result.

Example Input:

  • word1 = "abc"
  • word2 = "pqr"

Example Output:

  • apbqcr

Solution

To solve this problem, we iterate through both strings, appending characters alternately until one string is exhausted. Then, we append the remaining characters from the longer string.

class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder result = new StringBuilder();
int i = 0, j = 0;

while (i < word1.length() && j < word2.length()) {
result.append(word1.charAt(i++));
result.append(word2.charAt(j++));
}

if (i < word1.length()) {
result.append(word1.substring(i));
}

if (j < word2.length()) {
result.append(word2.substring(j));
}

return result.toString();
}
}

Testing the Code

As professional developers, it’s crucial to ensure our code is secure and functions as expected.

public class TestSolution {
public static void main(String[] args) {
Solution sol = new Solution();

// Test case 1
String word1 = “abc”;
String word2 = “pqr”;
assert sol.mergeAlternately(word1, word2).equals(“apbqcr”) : “Test case 1 failed”;

// Test case 2
word1 = “ab”;
word2 = “pqrs”;
assert sol.mergeAlternately(word1, word2).equals(“apbqrs”) : “Test case 2 failed”;

// Test case 3
word1 = “abcd”;
word2 = “pq”;
assert sol.mergeAlternately(word1, word2).equals(“apbqcd”) : “Test case 3 failed”;

System.out.println(“All test cases passed!”);
}
}

Conclusion

The “Merge Strings Alternately” problem highlights the importance of clear algorithmic thinking and robust testing. By ensuring our code is both secure and thoroughly tested, we maintain professional standards in software development. This approach not only solves the problem effectively but also guarantees reliability.


Kevin MARVILLE
French Developer and Digital Artisan

For more insights and coding solutions, follow my blog and join me on this journey towards excellence in software development.


Discover more from Kvnbbg.fr

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *