0

I have a string say

((C1 AND C2) OR C3 AND C4) 

now if input is '2' i am supposed to remove C2 and next operator which is OR, and rearrange the numbering... so output is

((C1 AND ) C2 AND C3).

**Test String input and output

----------STRING --------------------------- INPUT ---------------EXPECTED OUTPUT

1. (C1 AND C2 OR C3 AND C4)                <<3(Input)>>          (C1 AND C2 OR C3)

2.  C1 OR C2 AND (C3 OR C4) AND C5         <<2(Input)>>          C1 OR (C2 OR C3) AND C4

So i just need to delete the 'C' with the given input no and next operator if there is any , retain all brackets and re no the 'C' with ascending nos. this has to be done in a JS function

4

1 回答 1

2

只要输入保持一致,那么这些方面的内容可能会满足您的需求。我知道您说“保留所有括号”,但这会产生丑陋的输出,所以我选择更正括号。你可以很容易地取出那部分。

function handleInput(str, input){
  var inArray = str.split(' ');
  inArray.forEach(function(v,i,a){
    if(v.indexOf("C"+input) > -1){
      if(v.indexOf('(') > -1 || v.indexOf(')') > -1)
        inArray = fixParen(inArray, input, v, i);
      else if(i+2 < a.length){
        inArray.splice(i,2);
        inArray = fixNumbers(inArray);
      }
      else
        inArray.splice(i-1,2);
      console.log(inArray.join(' '));
    }
  });
}
function fixParen(inArray, input, elem, index){
  var elemArray = elem.split('');
  var parenNumber = 0;
  if(elem.indexOf('(') > -1){
    elemArray.forEach(function(v){
      if(v == '('){
        parenNumber++;
      }
    });
    for (var i = index+2; parenNumber > 0; i+=2){
      var tempElem = inArray[i].split('');
      var n = tempElem.indexOf(')');
      if(n > -1){
        tempElem.splice(n,1);
        inArray[i] = tempElem.join('');
        parenNumber--;
      }
    }
    inArray.splice(index,2);
    return fixNumbers(inArray);
  }
  else{
    elemArray.forEach(function(v){
      if(v == ')'){
        parenNumber++;
      }
    });
    for (var i = index-2; parenNumber > 0; i-=2){
      var tempElem = inArray[i].split('');
      var n = tempElem.indexOf('(');
      if(n > -1){
        tempElem.splice(n,1);
        inArray[i] = tempElem.join('');
        parenNumber--;
      }
    }
    inArray.splice(index,2);
    return fixNumbers(inArray);
  }
}
function fixNumbers(inArray){
  var count = 1;
  inArray.forEach(function(v,i,a){
    if(v.indexOf('C') > -1){
      var tempElem = v.split('');
      var n = tempElem.indexOf('C');
      tempElem.forEach(function(val,ind,arr){
        if(parseInt(val,10))
          tempElem.splice(ind,1);
      });
      tempElem.splice(n+1,0,count);
      inArray[i] = tempElem.join('');
      count ++;
    }
  });
  return inArray;
}

这实际上是一个比看起来简单得多的问题。首先,您应该注意字符串的每个重要部分均由“ ”分隔。这使我们可以使用.split(' ')为我们提供所有有用部分的精美数组。接下来,括号只能放在C减少所需逻辑量的元素上。然后,every在某个时候(有一个对应)项,允许我们完全忽略测试字符串的长度,因为我们可以假设存在一个带有匹配括号的元素。最后只有两种情况,它是最后一个C元素,因此我们删除了之前的运算符,或者它不是最后一个,我们删除了之后的一个。除了括号匹配,这个逻辑很短。

于 2013-03-24T07:34:30.157 回答