【问题标题】:Need Help to solve an string challenge C#, Java or JavaScript需要帮助来解决字符串挑战 C#、Java 或 JavaScript
【发布时间】:2020-09-03 02:06:14
【问题描述】:

我一直在尝试解决这个挑战,但我找不到解决方法。我以前解决过类似的问题,但我发现这特别困难,甚至试图在保持线性时间复杂度的同时解决。这是我显然失败的面试评估的一部分。

我将不胜感激。 谢谢

挑战来了

You are to parse the string into pieces that are no more than "pieceLength" characters long
INCLUDING the commas. 
If pieceLength = 3 the result for the above test string would be
result[0] = "1,2"
result[1] = ",3,"
result[2] = "5,8"
result[3] = ","
result[4] = "131"
result[5] = ",21"
result[6] = ",34"
You can look at the test above. This is a sample string and result, however
your code will be run with multiple input strings and piece length parameters.
Note how result[3] is just ",". Including any more characters would break apart 
the next number, 131, and that's not allowed.

【问题讨论】:

  • 对不起,我忘了放原始字符串。目标是将这个“1,2,3,5,8,131,21,34”解析为上述数组。

标签: arrays string parsing split


【解决方案1】:

执行此操作的一种方法是遍历字符串,查看下一个piecelength 之外的字符。如果这超出了字符串的结尾,或者是逗号,则没有问题,您可以将所有字符推到该点。否则从该位置向后迭代,直到找到逗号并将字符串推到逗号。如果没有找到逗号,则字符串的部分都是数字,可以推送到数组中:

let str = "1,2,3,5,8,131,21,34";

let pieces = (str, piecelength) => {
  let res = [];
  for (let i = 0; i < str.length;) {
    if (i + piecelength >= str.length || str[i + piecelength] == ',') {
      // no problem, just grab the characters
      res.push(str.substring(i, Math.min(i + piecelength, str.length)));
      i += piecelength;
    } else {
      // search back for the last comma
      for (j = piecelength - 1; j >= 0; j--) {
        if (str[i + j] == ',') {
          res.push(str.substr(i, j + 1));
          i += j + 1;
          break;
        }
      }
      if (j == -1) {
        // didn't find a comma, everything must be a digit
        res.push(str.substr(i, piecelength));
        i += piecelength;
      }
    }
  }
  return res;
}

console.log(pieces(str, 3));
console.log(pieces(str, 4));

【讨论】:

  • @user6372748 不用担心 - 我很高兴它有帮助。