844. Backspace String Compare

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

Example 1:

Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:

Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".

Example 3:

Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:

Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.

Follow up:

  • Can you solve it in O(N) time and O(1) space?

    题目没看太懂,看完案例看懂了。字符'#'代表退格符,如果在#号前有非#号字符的话就要消去。这样子题目就很浅显易懂了,直接把字符串一个一个对比,如果遇到非#号字符就保存,遇到#号并且#号前有字符的话就消去,最后再比较两个字符串的字符是否相等就行。

     1 void modifyString(char* S) {
     2     int cur = 0;
     3     for(int i=0;S[i]!='\0';i++) {
     4         if(S[i]!='#') {
     5             S[cur++] = S[i];
     6         }     
     7         else if(S[i]=='#' && cur>0) {
     8             cur--;
     9         }
    10     }
    11     S[cur] = '\0';//因为字符串数组最后的一个字符必须是'\0'
    12 }
    13 bool backspaceCompare(char* S, char* T) {
    14     modifyString(S);
    15     modifyString(T);
    16     
    17     if(strcmp(S,T)==0){//strcmp函数用于比较两个字符串
    18         return true;
    19     }else{
    20         return false;
    21     }
    22 }

     

     

     


     

posted @ 2018-11-14 15:04  杜王町上班族  阅读(177)  评论(0编辑  收藏  举报