알고리즘 문제 풀이
1768. Merge Strings Alternately
가나무마
2021. 6. 15. 22:56
Merge Strings Alternately - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
번갈아가면서 문자열합치기.
[내가 푼 코드]
class Solution {
public String mergeAlternately(String word1, String word2) {
String longerStr = word1.length() > word2.length() ? word1 :word2;
String shortStr = longerStr == word1 ? word2 : word1;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < shortStr.length(); i++) {
sb.append(word1.charAt(i));
sb.append(word2.charAt(i));
}
if (longerStr.length() == shortStr.length()) {
return sb.toString();
} else {
sb.append(longerStr.substring(shortStr.length()));
}
return sb.toString();
}
}
짧은 문자열 길이만큼 문자를 붙여줍니다.
"ab", "cdef"면 "acbd"가 됩니다.
후에 남은 문자열을 붙여줍니다.
class Solution {
public String mergeAlternately(String w1, String w2) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < w1.length() || i < w2.length(); ++i) {
if (i < w1.length())
res.append(w1.charAt(i));
if (i < w2.length())
res.append(w2.charAt(i));
}
return res.toString();
}
}
간단하면서도 엄청 좋아보이는 답안.
반복할 때마다 길이를 체크해서 계속 붙입니다.