LeetCode #1047 RemoveAllAdjacentDuplicatesInString. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,그래프,Graph,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접, 데이터베이스, sql, query, 쿼리
Runtime: 56 ms, faster than 23.15% of C++ online submissions for Remove All Adjacent Duplicates In String.
Memory Usage: 11.4 MB, less than 100.00% of C++ online submissions for Remove All Adjacent Duplicates In String.
LeetCode #1047
Q.
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
소문자로된 문자열 S가 주어지고, 두개의 같은 문자가 붙어있는 것을 찾아서 지운다.
해당 문자에 똑같은 것이 붙은게 없을 때까지 반복한다.
마지막 문자를 반환한다. 답은 1개라는 것을 보장함
Example 1:
Input: "abbaca"
Output: "ca"
Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Note:
- 1 <= S.length <= 20000
- S consists only of English lowercase letters.
Process
// Process 1 (Better performance)
//1. Input string S
//2. Iterate all char
// 2.1. Check if adjacent chars are duplicated or not
// 2.1.1. If so -> erase them and adjust index
//3. Return result
// Process 2 (Worse performance - Recursive)
//1. Input string S
//2. Call recursiveFunc
//3. Return resultString
// **Recursive
//1. Input string
//2. Iterate all char
// 2.1. Check if it's adjacent, equal two letters
// 3.1.1. If so -> Delete them and Call recursive
//3. Return string
// 처리과정
//1. 문자열 S, T 입력받는다.
//2. 시작부터 끝까지 반복한다.
// 2.1. 해당 문자가 # 인지 확인해서
// 2.1.1. # 이면 -> 앞의 글자를 지운다
// 2.2. # 글자 지운다
//3. 같은지 확인해서 결과 반환한다.
Code.. lemme see example code!!!
코드.. 예제코드를 보자!!!
class Solution {
public:
string removeDuplicates(string S) {
for (int i = 1; i < S.size(); ++i) {
if (S[i] == S[i - 1]) {
S.erase(i-1, 2);
if (i - 1 > 0)
i -= 2;
else {
i -= 1;
}
}
}
return S;
}
// public:
// string removeDuplicates(string S) {
// return recursiveRemoveDuplicates(S);
// }
// private:
// string recursiveRemoveDuplicates(string &letters) {
// bool isDone = false;
// for (int i = 0; !isDone && i < letters.length() - 1; ++i) {
// if (letters[i] == letters[i + 1]) {
// letters.erase(i, 2);
// if (letters.length() > 0)
// letters = recursiveRemoveDuplicates(letters);
// isDone = true;
// }
// }
// return letters;
// }
};
Something else you might like...?
2019/02/19 - [Life/Health care] - Lysine 라이신 usage/side effects/dosage 효과/효능/부작용/성인,소아 용법, 복용법
2019/02/28 - [Life/Health care] - Vitamin K, 비타민 K usage/side effects/dosage 효능/부작용/성인,소아 용법