
#은 앞에 문자를 지우는 역할이다. #이 자기 역할을 모두 수행하고 난 후의 문자열을 비교하는 문제
소스코드
class Solution {
public:
    bool backspaceCompare(string S, string T) {
        stack<char> s_st, t_st;
        for(int i = 0; i < S.length(); i++){
            if(S[i] != '#') s_st.push(S[i]);
            else if(!s_st.empty()){
                s_st.pop();
            }
        }
        for(int i = 0; i < T.length(); i++){
            if(T[i] != '#') t_st.push(T[i]);
            else if(!t_st.empty()){
                t_st.pop();
            }
        }
        if(s_st.empty() && t_st.empty()) return true;
        else{
            while(!s_st.empty() || !t_st.empty()){
                if(s_st.empty() || t_st.empty()) return false;
                if(s_st.top() != t_st.top()) return false;
                s_st.pop(); t_st.pop();
            }
        }
        return true;
    }
};
1. 스택을 이용해서 풀었다.
2. S와 T 각각 문자면 stack에 넣고, #이면 앞에 문자를 하나씩 지웠다(stack이 비지 않았을 때만).
3. 두 스택에서 하나씩 꺼내가며 # 처리된 후 두 문자열이 같은지 비교를 했다.
'개인 공부 > 코딩테스트' 카테고리의 다른 글
| [C++][leetcode] Diameter of Binary Tree :: seoftware (0) | 2020.04.12 | 
|---|---|
| [C++][leetcode] Min Stack :: seoftware (0) | 2020.04.12 | 
| [c++][백준] 1475번 방 번호 :: seoftware (0) | 2020.04.10 | 
| [C++][백준] 14502번 연구소 :: seoftware (0) | 2020.04.10 | 
| [C++][leetcode] Middle of the linked list :: seoftware (0) | 2020.04.09 | 
 
										
									 
										
									 
										
									 
										
									
댓글