반응형
Recent Posts
Notice
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Algorithm
- binary tree
- Array
- programmers
- 재귀함수
- PCCP
- dfs
- leetcode
- DP
- 깊이우선탐색
- 리트코드
- priority queue
- 브루트포스
- string
- 우선순위 큐
- coding
- ArrayList
- Java
- greedy
- HashMap
- hashset
- recursion
- two pointers
- 부분배열
- 알고리즘
Archives
- Today
- Total
지식창고
[Java]LeetCode 791. Custom Sort String 본문
728x90
반응형
Leetcode 791. Custom Sort String - Java
문제 :
s에 있는 문자열을 order 기준으로 정렬
Input: order = "cba", s = "abcd"
Output: "cbad"
문자열 s 에서 각 알파벳이 몇 번 나왔는지 count 배열에 저장해 관리한다.
int[] cnt = new int[128];
for(char ch : s.toCharArray()) {
cnt[ch]++;
}
정렬의 기준이 되는 문자열 order에 알파벳을 빠짐없이 들어갈 수 있도록 더해준다.
order += "abcdefghijklmnopqrstuvwxyz";
Output을 저장할 변수 result를 선언한다.
order를 기준으로 cnt 배열을 확인하며 결과 값에 저장한다.
for(char ch : order.toCharArray()){
while(cnt[ch]-- > 0) {
result.append(ch);
}
}
결 과
class Solution {
public String customSortString(String order, String s) {
int[] cnt = new int[128];
StringBuilder result = new StringBuilder();
for(char ch : s.toCharArray()){ // 목표 문장 저장
cnt[ch]++;
}
order += "abcdefghijklmnopqrstuvwxyz";
for(char ch : order.toCharArray()){
while(cnt[ch]-- > 0){
result.append(ch);
}
}
return result.toString();
}
}
728x90
반응형
'Algorithm > Leetcode' 카테고리의 다른 글
[Java] LeetCode 452. Minimum Number of Arrows to Burst Balloons (0) | 2023.01.06 |
---|---|
[Java]LeetCode 2244. Minimum Rounds to Complete All Tasks (2) | 2023.01.04 |
[Java]LeetCode 1834. Single-Threaded CPU (0) | 2022.12.29 |
[Java]LeetCode 1962. Remove Stones to Minimize the Total (0) | 2022.12.28 |
[Java]LeetCode 817. Linked List Components (0) | 2022.12.24 |
Comments