-
[LeetCode] 1417. Reformat The StringLeetCode 2021. 10. 25. 16:36728x90
https://leetcode.com/problems/reformat-the-string/
Reformat The String - 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
Reformat The String - Easy


알파벳 소문자와 숫자로만 된 String이 주어졌을때,
알파벳/숫자/알파벳/숫자... 또는
숫자/알파벳/숫자/알파벳... 으로 알파벳과 숫자가번갈아가도록 String을 재조합하는 문제다.
String을 훑으며 알파벳/숫자스택에 각각 추가해주고
ret 에 하나씩 번갈아가며 추가해주면 된다.
약간의 트릭은 먼저 알파벳부터 추가를 해준다.
이러면 숫자가 제일 뒤에 남게 되는게, 스택에 알파벳이 남아있으면 알파벳만 추가해준다.
스택에 숫자가 남아있다면 숫자 + ret 으로 숫자를 앞에 추가해주자.
전체 풀이 코드
class Solution { public: string reformat(string s) { string ret; stack<char> a,n; for (char c:s) c>='a'?a.push(c):n.push(c); while(!a.empty() && !n.empty()) { ret += a.top(); ret += n.top(); a.pop(); n.pop(); } return a.size()+n.size()>1?"":a.empty()?n.empty()?ret:n.top()+ret:ret+a.top(); } };'LeetCode' 카테고리의 다른 글
[LeetCode] 226. Invert Binary Tree (0) 2021.10.26 [LeetCode] 1260. Shift 2D Grid (0) 2021.10.25 [LeetCode] 1007. Minimum Domino Rotations For Equal Row (0) 2021.10.25 [LeetCode] 155. Min Stack (0) 2021.10.25 [LeetCode] 215. Kth Largest Element in an Array (0) 2021.10.22