给出两个输入流inputA
和inputB
(包含退格符),如果两个输入流最后的结果相等,输出YES
,否则输出NO
。
样例
样例1
输入: inputA = "abcde<<" 和 inputB = "abcd<e<"
输出: "YES"
解释:
inputA和inputB最后的结果都为"abc",故返回"YES"。
样例2
输入: inputA = "a<<bc" 和 inputB = "abc<"
输出: "NO"
解释:
inputA最后的结果为"bc",inputB最后的结果为"ab",故返回"NO"。
注意事项
- 输入字符只包括小写字母和
'<'
。 - 输入流长度不超过
10000
。
解题思路:
利用栈来操作退格。
public class Solution {
/**
* @param inputA: Input stream A
* @param inputB: Input stream B
* @return: The answer
*/
public String inputStream(String inputA, String inputB) {
// Write your code here
String res1 = helper(inputA);
String res2 = helper(inputB);
if((res1 == null && res2 == null) || res1.equals(res2))
return "YES";
return "NO";
}
private String helper(String str){
Stack<Character> stack = new Stack<>();
char[] chars = str.toCharArray();
for(int i=0; i<chars.length; i++){
if(chars[i] == '<'){
if(!stack.isEmpty())
stack.pop();
}else{
stack.push(chars[i]);
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.toString();
}
}