728x90
문제
i : 임의의 문자열 / o : 연속된 중복문자 개수만큼 숫자를 넣고, 해당 문자를 붙여서 문자열 리턴
조건
1) 연속된 문자는 3개 이상일 경우에만 숫자+문자조합
2) 빈 문자열은 빈 문자열 리턴
3) stack과 queue를 사용해서 코드작성
코드
1. 풀어서 만든 코드
import java.util.*;
public class Solution {
public String compressString(String str) {
// TODO:
if(str.length()==0) return str;
String[] arr = str.split(""); // 문자열을 각 문자로 나눈 배열로 변환
Queue<String> queue = new LinkedList<>(Arrays.asList(arr)); // Queue에 문자열로 만든 배열을 때려박음
Stack<String> stack = new Stack<>(); // 연속된 중복문자열의 첫번째 문자를 담음. 중복이 끝나면 pop할것임 (즉, 항상 size가 0 또는 1인 상태 유지)
String result = ""; // 최종 반환할 String
int count = 1; // 중복 개수. 초기값은 1로 설정(빈 스택일 경우 queue.poll한것 stack에 넣기만 할 것이므로)
while(!queue.isEmpty()) { //queue가 빌 때까지 반복
//1. 빈 스택인 상태면 => queue에서 첫번째거 빼서 stack에 넣어주자
if(stack.isEmpty()) stack.push(queue.poll());
//2. stack에 있는 문자열과 queue의 첫 문자열이 같을 경우 => queue에서 하나 지워주고, 중복개수count를 1 올려주자
if(stack.peek().equals(queue.peek())) {
queue.poll();
count++;
}
//3. stack의 문자열과 queue의 첫 문자열이 다르면,
if(!stack.peek().equals(queue.peek())) {
// count가 2보다 클 경우 => 결과값에 현재까지의 count를 더하고, stack에 있는 문자열을 빼내서 더하자
if(count>2) result = result + count + stack.pop();
// count가 2라면 => 결과값에 stack의 문자열을 두 번 붙여주고, stack을 비우자
else if(count==2) result = result + stack.peek() + stack.pop();
// count가 1이라면(기본값) => 결과값에 stack의 문자열을 한 번 붙여주고, stack을 비우자
else if(count<2) result = result + stack.pop();
// count를 다시 1로 초기화 해주자
count=1;
}
}
// while(!queue.isEmpty()) result += queue.poll(); //queue 확인용. queue엔 arr가 잘 들갔음
return result;
}
}
2. 간소화 코드
import java.util.*;
public class Solution {
public String compressString(String str) {
String[] arr = str.split("");
Queue<String> queue = new LinkedList<>(Arrays.asList(arr));
Stack<String> stack = new Stack<>();
String result = "";
int count = 1;
while(!queue.isEmpty()) {
if(stack.isEmpty()) stack.push(queue.poll());
if(stack.peek().equals(queue.peek())) {
queue.poll();
count++;
}
if(!stack.peek().equals(queue.peek())) {
if(count>2) result = result + count + stack.pop();
else if(count==2) result = result + stack.peek() + stack.pop();
else result = result + stack.pop();
count=1;
}
}
return result;
}
}
728x90
'알고리즘 저장소 (일반방식과 나만의 풀이) > JAVA' 카테고리의 다른 글
tiling 알고리즘 (0) | 2022.09.01 |
---|---|
트리 BFS 코드 (0) | 2022.08.24 |
버블 정렬(Bubble sort) 구현하기 (0) | 2022.08.22 |
바빌로니아 점화식 (0) | 2022.08.12 |
카이사르 암호 (0) | 2022.08.09 |