Leetcode.844. Compare strings with backspace

844. Compare strings with backspace

Given Sand Ttwo strings, when they are inputted to a blank text editor, it is determined whether the two are equal, and returns the result. #Represents the backspace character.

Note: If you enter a backspace character for empty text, the text will remain empty.

Example 1:

输入:S = "ab#c", T = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。

Example 2:

输入:S = "ab##", T = "c#d#"
输出:true
解释:S 和 T 都会变成 “”。

Example 3:

输入:S = "a##c", T = "#a#c"
输出:true
解释:S 和 T 都会变成 “c”。

Example 4:

输入:S = "a#c", T = "b"
输出:false
解释:S 会变成 “c”,但 T 仍然是 “b”。

prompt:

  • 1 <= S.length <= 200
  • 1 <= T.length <= 200
  • S and T only contain lowercase letters and the character'#'.

Advanced:

You can use the O(N)time complexity and O(1)space complexity of solving this problem?

Method 1: Refactor the string

bool backspaceCompare(char* S, char* T) {
    
    
    return strcmp(build(S), build(T)) == 0;
}

char* build(char* str) {
    
    
    int n = strlen(str), len = 0;
    char* ret = malloc(sizeof(char) * (n + 1));
    for (int i = 0; i < n; i++) {
    
    
        if (str[i] != '#') {
    
    
            ret[len++] = str[i];
        } else if (len > 0) {
    
    
            len--;
        }
    }
    ret[len] = '\0';
    return ret;
}

Method 2: Double pointer

Whether a character is deleted or not depends only on whether there is something behind the character #, so we can traverse from back to front. In this way, it can be immediately determined whether the character is deleted.

bool backspaceCompare(char* S, char* T) {
    
    
    int i = strlen(S) - 1, j = strlen(T) - 1;
    int skipS = 0, skipT = 0;

    while (i >= 0 || j >= 0) {
    
    
        while (i >= 0) {
    
    
            if (S[i] == '#') {
    
    
                skipS++, i--;
            } else if (skipS > 0) {
    
    
                skipS--, i--;
            } else {
    
    
                break;
            }
        }
        while (j >= 0) {
    
    
            if (T[j] == '#') {
    
    
                skipT++, j--;
            } else if (skipT > 0) {
    
    
                skipT--, j--;
            } else {
    
    
                break;
            }
        }
        if (i >= 0 && j >= 0) {
    
    
            if (S[i] != T[j]) {
    
    
                return false;
            }
        } else {
    
    
            if (i >= 0 || j >= 0) {
    
    
                return false;
            }
        }
        i--, j--;
    }
    return true;
}

Leetcode official

Guess you like

Origin blog.csdn.net/e891377/article/details/109154391