Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- rds
- 병목
- cloudwatch
- sns
- serverless
- lambda
- Validation
- fcm
- amazonqcli
- Lamda
- IaC
- aws
- CHECK
- kubernetes
- terraform
- SageMaker
Archives
- Today
- Total
잡다한 IT 지식
1768. Merge Strings Alternately 본문
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();
}
}
간단하면서도 엄청 좋아보이는 답안.
반복할 때마다 길이를 체크해서 계속 붙입니다.
'알고리즘 문제 풀이' 카테고리의 다른 글
프로그래머스 약수의 개수와 덧셈 (0) | 2021.07.24 |
---|---|
104. Maximum Depth of Binary Tree (0) | 2021.06.29 |
1051. Height Checker (0) | 2021.06.15 |
1897. Redistribute Characters to Make All Strings Equal (0) | 2021.06.14 |
완주하지 못한 선수 (0) | 2021.06.12 |