문자열 code가 주어집니다. code를 앞에서부터 읽으면서 만약 문자가 "1"이면 mode를 바꿉니다. mode에 따라 code를 읽어가면서 문자열 ret을 만들어냅니다. mode는 0과 1이 있으며, idx를 0 부터 code의 길이 - 1 까지 1씩 키워나가면서 code[idx]의 값에 따라 다음과 같이 행동합니다.
단, 시작할 때 mode는 0이며, return 하려는 ret가 만약 빈 문자열이라면 대신 "EMPTY"를 return 합니다.
1 ≤ code의 길이 ≤ 100,000 code는 알파벳 소문자 또는 "1"로 이루어진 문자열입니다.
| code | result |
| "abc1abc1abc" | "acbac" |
class Solution { public String solution(String code) { String[] slist = code.split(""); String ret = ""; int mode = 0; for (int i=0;i<slist.length;i++) { if(mode == 0) { if(!slist[i].equals("1") && i%2 == 0) { ret += slist[i]; }else if (slist[i].equals("1")) { mode = 1; } }else { if(!slist[i].equals("1") && i%2 == 1) { ret += slist[i]; }else if (slist[i].equals("1")) { mode = 0; } } } return (ret.length()!=0)?(ret):("EMPTY"); } }
class Solution { public String solution(String code) { StringBuilder answer = new StringBuilder(); int mode = 0; for (int i = 0; i < code.length(); i++) { char current = code.charAt(i); if (current == '1') { mode = mode == 0 ? 1 : 0; continue; } if (i % 2 == mode) { answer.append(current); } } return answer.length() == 0 ? "EMPTY" : answer.toString(); } }
https://school.programmers.co.kr/learn/courses/30/lessons/181932