Given two strings of S and T, when they are input into a blank text editor, determine whether they are equal, and return the result. # Represents the backspace character.
Note: If you enter a backspace character for empty text, the text will remain empty.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T will become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T will become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T will become "c".
Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S will become "c", but T will still be "b".
prompt:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and the character'#'.
Source: LeetCode
Link: https://leetcode-cn.com/problems/backspace-string-compare
I made this question by accident after reading the idea of an up master at station b. I gave the two statistical names sspace and tspace, and compared them from back to front. When the # number is encountered, it will increase by 1, and vice versa. Subtract 1 and compare the corresponding bits of the two strings when they are both 0, and return false if they are different.
code show as below:
/**
* @param {string} S
* @param {string} T
* @return {boolean}
*/
var backspaceCompare = function(S, T) {
var i=S.length-1;
var j=T.length-1;;
var sspace=0;
var tspace=0;
while(i>=0||j>=0){
while(i>=0){
if(S[i]=='#'){
sspace++;
i--;
}else if(sspace>0){
sspace--;
i--;
}else{
break;
}
}
while(j>=0){
if(T[j]=='#'){
tspace++;
j--;
}else if(tspace>0){
tspace--;
j--;
}else{
break;
}
}
if(S[i]!==T[j]){
return false;
}
if(i<0&&j>=0||i>=0&&j<0){
return false;
}
i--;
j--;
}
return true;
};
After reading the solutions of others, I think it is indeed easier to use regular expressions. For example, the code of this old man, for your reference:
/**
* @param {string} S
* @param {string} T
* @return {boolean}
*/
var backspaceCompare = function(S, T) {
let reg = /[a-z](?=\#)\#/g;
S = S.replace(/^\#/,'').replace(reg, '');
T = T.replace(/^\#/,'').replace(reg, '');
if(!S.includes('#') && !T.includes('#')){
return S == T;
}
return backspaceCompare(S, T);
};
作者:caoyq0521
链接:https://leetcode-cn.com/problems/backspace-string-compare/solution/bi-jiao-han-tui-ge-de-zi-fu-chuan-by-caoyq0521/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。