力扣:844:比较含退格的字符串

This commit is contained in:
huangge1199 2021-04-01 11:36:32 +08:00
parent 260741e974
commit 9d1ee7ea99
2 changed files with 159 additions and 0 deletions

View File

@ -0,0 +1,102 @@
//给定 S T 两个字符串当它们分别被输入到空白的文本编辑器后判断二者是否相等并返回结果 # 代表退格字符
//
// 注意如果对空文本输入退格字符文本继续为空
//
//
//
// 示例 1
//
//
//输入S = "ab#c", T = "ad#c"
//输出true
//解释S T 都会变成 ac
//
//
// 示例 2
//
//
//输入S = "ab##", T = "c#d#"
//输出true
//解释S T 都会变成
//
//
// 示例 3
//
//
//输入S = "a##c", T = "#a#c"
//输出true
//解释S T 都会变成 c
//
//
// 示例 4
//
//
//输入S = "a#c", T = "b"
//输出false
//解释S 会变成 c T 仍然是 b
//
//
//
// 提示
//
//
// 1 <= S.length <= 200
// 1 <= T.length <= 200
// S T 只含有小写字母以及字符 '#'
//
//
//
//
// 进阶
//
//
// 你可以用 O(N) 的时间复杂度和 O(1) 的空间复杂度解决该问题吗
//
//
//
// Related Topics 双指针
// 👍 276 👎 0
package leetcode.editor.cn;
import java.util.Stack;
//844:比较含退格的字符串
public class BackspaceStringCompare {
public static void main(String[] args) {
//测试代码
Solution solution = new BackspaceStringCompare().new Solution();
solution.backspaceCompare("a##c", "#a#c");
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean backspaceCompare(String S, String T) {
S = getResult(S);
T = getResult(T);
return S.equals(T);
}
private String getResult(String str) {
Stack<Character> stack = new Stack<>();
int length = str.length();
for (char ch : str.toCharArray()) {
if (ch == '#') {
if(!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(ch);
}
}
str = "";
while (!stack.isEmpty()) {
str += stack.pop().toString();
}
return str;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,57 @@
<p>给定 <code>S</code><code>T</code> 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 <code>#</code> 代表退格字符。</p>
<p><strong>注意:</strong>如果对空文本输入退格字符,文本继续为空。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>S = "ab#c", T = "ad#c"
<strong>输出:</strong>true
<strong>解释:</strong>S 和 T 都会变成 “ac”。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>S = "ab##", T = "c#d#"
<strong>输出:</strong>true
<strong>解释:</strong>S 和 T 都会变成 “”。
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>S = "a##c", T = "#a#c"
<strong>输出:</strong>true
<strong>解释:</strong>S 和 T 都会变成 “c”。
</pre>
<p><strong>示例 4</strong></p>
<pre>
<strong>输入:</strong>S = "a#c", T = "b"
<strong>输出:</strong>false
<strong>解释:</strong>S 会变成 “c”但 T 仍然是 “b”。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= S.length <= 200</code></li>
<li><code>1 <= T.length <= 200</code></li>
<li><code>S</code><code>T</code> 只含有小写字母以及字符 <code>'#'</code></li>
</ul>
<p> </p>
<p><strong>进阶:</strong></p>
<ul>
<li>你可以用 <code>O(N)</code> 的时间复杂度和 <code>O(1)</code> 的空间复杂度解决该问题吗?</li>
</ul>
<p> </p>
<div><div>Related Topics</div><div><li></li><li>双指针</li></div></div>\n<div><li>👍 276</li><li>👎 0</li></div>