728x90
반응형
Java
import java.util.*;
class Solution
{
public int solution(String s){
if(s.length() % 2 == 1)
return 0;
Stack<Integer> stack = new Stack();
int before = 0;
int i = 0;
while(i < s.length()){
if(before == s.charAt(i)){
stack.pop();
}else{
stack.push((int)s.charAt(i));
}
if(stack.size() > 0)
before = stack.peek();
else
before = 0;
i++;
}
return stack.size() == 0 ? 1 : 0;
}
/*효율성 탈락
public int solution(String s)
{
int answer = 0;
StringBuffer st = new StringBuffer(s);
for(int i = st.length() - 1; i > 0;){
if (st.charAt(i - 1) == st.charAt(i)){
st = st.replace(i - 1, i + 1, "");
i = st.length() - 1;
}else{
i--;
}
}
return st.length() == 0 ? 1: 0;
}*/
}
Python
def solution(s):
answer = 0
if len(s) % 2 == 1: return 0
i = 1
before = s[0]
stack = list()
stack.append(before)
while i < len(s):
if before == s[i]:
stack.pop()
else:
stack.append(s[i])
if len(stack) > 0:
before = stack[-1]
else:
before = ''
i += 1
return 1 if len(stack) == 0 else 0
728x90
반응형