• 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]!='';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] = '';//因为字符串数组最后的一个字符必须是''
      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 }

       

       


       

  • 相关阅读:
    C复制字符串
    C语言分解数组
    perlCGI编程之测试环境
    linux下c语言 读取文件
    C++的组合(Composite)模式
    C#GDI+绘制多行文本和格式化文本
    shell中引号的应用
    perlCGI编程之Apache服务器安装配置
    求二叉树的深度
    perlCGI编程之页面参数传递
  • 原文地址:https://www.cnblogs.com/real1587/p/9958063.html
Copyright © 2020-2023  润新知