Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character

huangapple go评论200阅读模式
英文:

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character

问题

class Solution {
    public boolean backspaceCompare(String S, String T) {
        
        Stack<Character> stack1 = new Stack<Character>();
        Stack<Character> stack2 = new Stack<Character>();
        for(int i=0; i<S.length(); i++){
            if(S.charAt(i)!='#'){
                stack1.push(S.charAt(i));
            }else{
                if(!stack1.isEmpty()){
                    stack1.pop();
                }
            }
        }
        for(int j=0; j<T.length(); j++){
            if(T.charAt(j)!='#'){
                stack2.push(T.charAt(j));
            }else{
                if(!stack2.isEmpty()){
                    stack2.pop();
                }
            }
        }
        
        return stack1.equals(stack2);
    }
}

This code is meant to compare two strings, S and T, after processing their characters according to the following rule: If the character is not a backspace character (#), it's added to the corresponding stack. If it's a backspace character and the stack is not empty, a character is removed from the stack. After processing both strings, the stacks are compared for equality to determine if the final processed strings are the same.

英文:
Example 1:

Input: S = &quot;ab#c&quot;, T = &quot;ad#c&quot;
Output: true
Explanation: Both S and T become &quot;ac&quot;.
Example 2:

Input: S = &quot;ab##&quot;, T = &quot;c#d#&quot;
Output: true
Explanation: Both S and T become &quot;&quot;.
Example 3:

Input: S = &quot;a##c&quot;, T = &quot;#a#c&quot;
Output: true
Explanation: Both S and T become &quot;c&quot;.
Example 4:

Input: S = &quot;a#c&quot;, T = &quot;b&quot;
Output: false
Explanation: S becomes &quot;c&quot; while T becomes &quot;b&quot;.
class Solution {
    public boolean backspaceCompare(String S, String T) {
        
        Stack&lt;Character&gt; stack1 = new Stack&lt;Character&gt;();
        Stack&lt;Character&gt; stack2 = new Stack&lt;Character&gt;();
        for(int i=0;i&lt;S.length();i++){
            
            
            if(S.charAt(i)!=&#39;#&#39;){
            stack1.push(S.charAt(i));
                
        }else{
                    stack1.pop();
                }
        }
        for(int j =0;j&lt;T.length();j++){
                       
            if(T.charAt(j)!=&#39;#&#39;){
            stack2.push(S.charAt(j));
                
        }else 
                stack2.pop();
        }
        
        if(stack1==stack2)
            return true;
        return false;
    }
}

my output is false and answer should be true why is this not working?

答案1

得分: 1

第一个错误是将所有字符都推到堆栈上,放在 if 语句的外面。

此外,在从堆栈中移除项目之前,您应该检查堆栈是否为空。
否则会抛出 EmptyStackException。

// stack1.push(S.charAt(i)); &lt;-- 删除此行
if (S.charAt(i)!=&#39;#&#39;) {
   stack1.push(S.charAt(i));
}else if (!stack1.isEmpty()) { // &lt;-- 添加此检查
   stack1.pop();
}

第二个错误是你不能使用 == 来比较两个堆栈的内容,应该使用 .equals 方法代替:

if(stack1.equals(stack2))
英文:

The first mistake is pushing all the characters on the stack outside of the if statement.

Also you should check if stack is empty before removing items from it.
Otherwise EmptyStackException is thrown.

// stack1.push(S.charAt(i)); &lt;-- remove this line
if (S.charAt(i)!=&#39;#&#39;) {
   stack1.push(S.charAt(i));
}else if (!stack1.isEmpty()) { // &lt;-- add this check
   stack1.pop();
}

The second mistake is you can't use == to compare the contents of two stacks, use .equals method instead:

if(stack1.equals(stack2))

答案2

得分: 1

JonI的回答正确地解决了代码中的错误,但我还想提出一些其他问题:

  • 您应该使用一个辅助方法来消除重复的代码。

  • 您应该使用 Deque 而不是 Stack。Javadoc 中是这样说的。

  • 而不是使用 Stack/Deque,我建议使用 StringBuilder,以避免必须对 char 值进行装箱。

类似这样的代码:

public boolean backspaceCompare(String s, String t) {
    return applyBackspace(s).equals(applyBackspace(t));
}

private static String applyBackspace(String s) {
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != '#')
            buf.append(s.charAt(i));
        else if (buf.length() != 0)
            buf.setLength(buf.length() - 1);
    }
    return buf.toString();
}
英文:

Answer by Joni correctly addresses the errors in the code, however there are some other issues I'd like to address:

  • You should use a helper method to eliminate repeating the same code.

  • You should use Deque instead of Stack. The javadoc says so.

  • Instead of using Stack/Deque, I'd recommend using StringBuilder, to prevent having to box the char values.

Something like this:

public boolean backspaceCompare(String s, String t) {
	return applyBackspace(s).equals(applyBackspace(t));
}

private static String applyBackspace(String s) {
	StringBuilder buf = new StringBuilder();
	for (int i = 0; i &lt; s.length(); i++) {
		if (s.charAt(i) != &#39;#&#39;)
			buf.append(s.charAt(i));
		else if (buf.length() != 0)
			buf.setLength(buf.length() - 1);
	}
	return buf.toString();
}

答案3

得分: 0

你的想法是有效的,但是复制字符串到堆栈中是昂贵且不必要的。如果你从末尾开始向前处理,就不需要额外的存储:

// 给定字符串长度或有效字符位置,返回前一个有效字符的位置,如果没有则返回-1
public static int previousCharPos(String s, int pos)
{
    int bs = 0; // 匹配的退格数
    while (pos > 0) {
        --pos;
        if (s.charAt(pos) == '#') {
            ++bs;
        } else if (bs <= 0) {
            return pos;
        } else {
            --bs;
        }
    }
    return -1;
}

public static boolean backspaceCompare(String S, String T)
{
    int spos = previousCharPos(S, S.length());
    int tpos = previousCharPos(T, T.length());
    while (spos >= 0 && tpos >= 0) {
        if (S.charAt(spos) != T.charAt(tpos)) {
            return false;
        }
        spos = previousCharPos(S, spos);
        tpos = previousCharPos(T, tpos);
    }
    return spos == tpos;
}
英文:

Your idea works, but it's expensive and unnecessary to copy the strings into stacks. If you work backwards from the end, no extra storage is necessary:

//given the string length or a valid character position, return
//the position of the previous valid character, or -1 if none
public static int previousCharPos(String s, int pos)
{
	int bs=0; // number of backspaces to match
	while(pos&gt;0) {
		--pos;
		if (s.charAt(pos)==&#39;#&#39;) {
			++bs;
		} else if (bs &lt;= 0) {
			return pos;
		} else {
			--bs;
		}
	}
	return -1;
}

public static boolean backspaceCompare(String S, String T)
{
	int spos = previousCharPos(S,S.length());
	int tpos = previousCharPos(T,T.length());
	while(spos &gt;= 0 &amp;&amp; tpos &gt;= 0) {
		if (S.charAt(spos) != T.charAt(tpos)) {
			return false;
		}
		spos = previousCharPos(S,spos);
		tpos = previousCharPos(T,tpos);
	}
	return spos == tpos;
}

huangapple
  • 本文由 发表于 2020年4月9日 19:00:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/61119616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定