Daily question: Implement method fn. When encountering a backspace character, delete the previous character. When encountering two backspace characters, delete the two characters.

Daily question

Please implement method fn according to the following requirements. When encountering a backspace character, delete the previous character. When encountering two backspaces, delete the two characters:

// 比较含有退格的字符串,"<-"代表退格键,"<"和"-"均为正常字符 
// 输入:"a<-b<-", "c<-d<-",结果:true,解释:都为"" 
// 输入:"<-<-ab<-", "<-<-<-<-a",结果:true,解释:都为"a" 
// 输入:"<-<ab<-c", "<<-<a<-<-c",结果:false,解释:"<ac" !== "c" 
function fn(str1, str2) {
    
     }

Idea one:

  • Find consecutive "<-" characters in a string and delete the preceding characters
  • Define a function specifically to handle such strings
  • Finally compare the converted substrings.
function fn(str1,str2){
    
    
  let leftr = FromatStr(str1);
  let right = FromatStr(str2);
  return leftr == right;
}

function FromatStr(str){
    
    
  let arr = str.split('');
  for(let i=0;i<arr.length-1;i++){
    
    
    if(arr[i]=='<' && arr[i+1]=='-'){
    
    
      if(arr[i-1]){
    
    
        arr.splice(i-1,3,'');//添加''是防止索引塌陷
      }else{
    
    
        arr.splice(i,2,'');//添加''是防止索引塌陷
      }
    }
  }
  return arr.join('');

Idea two:

  • Use a temporary array to achieve qualified characters
  • Delete this character when it encountersdelete key
  • Then jump directly to the next character and judge
function fn(str1,str2){
    
    
  let leftr = FromatStr(str1);
  let right = FromatStr(str2);
  return leftr == right;
}

function FromatStr(str){
    
    
  let arr = [];
  for(let i=0;i<str.length;i++){
    
    
    if(str[i]=='<' && str[i+1]=='-'){
    
    
      i++;//直接跳跃到下下个字符在判断
      arr.pop();
    }else{
    
    
      arr.push(str[i]);
    }
  }
  return arr.join('');
}


let result = fn("-a<-b<-","c<-d<-");
console.log(result);//false

Idea three

  • Use regular replacement
    Insert image description here

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/134977262