zoukankan      html  css  js  c++  java
  • 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 }

       

       


       

  • 相关阅读:
    python3数据库配置,远程连接mysql服务器
    Ubuntu 16.04安装JDK
    用Python从零开始创建区块链
    理解奇异值分解SVD和潜在语义索引LSI(Latent Semantic Indexing)
    gensim介绍(翻译)
    记一次浅拷贝的错误
    Heap queue algorithm
    Python
    python列表中插入字符串使用+号
    Linux(Ubuntu)使用 sudo apt-get install 命令安装软件的目录在哪?
  • 原文地址:https://www.cnblogs.com/real1587/p/9958063.html
Copyright © 2011-2022 走看看