【问题标题】:Find the index of each letter of a given string, and return the same index if the letter is repeated查找给定字符串的每个字母的索引,如果字母重复则返回相同的索引
【发布时间】:2020-08-21 10:38:56
【问题描述】:

我正在尝试解决一个相当简单的 kata,但发现自己陷入了一个有条件的问题。我正在尝试为不止一次具有相同字母的字符串返回相同的整数。

例如,对于字符串hello,它应该返回0.1.2.2.3

这是我目前的代码:

const wordPattern = word => {
  word = word.toLowerCase();
  let index =[]
  
  for(i=0; i<word.length; i++){
    index.includes(i) ? word(i) === index[i] : index.push(i)
  }
    
  return index 
}

提前非常感谢!

【问题讨论】:

  • 不应该是0,1,2,2,4吗?
  • 看起来像是招聘任务或练习(课程)任务,而您刚刚询问了答案。您是否尝试过自己解决?你尝试了什么?你在哪里失败了?尝试先学习。
  • 嗨,Adam,是的,正如您在上面的代码中看到的那样,是的,测试示例应该返回 0,1,2,2,3。

标签: javascript string if-statement conditional-statements


【解决方案1】:

我会使用一个对象,因为它使我能够将键(字母)映射到值(分配给该字母的整数):

const wordPattern = word => {
  word = word.toLowerCase();
  const map = {}
  const output = []
  let counter = 0
  
  for(i=0; i<word.length; i++){
    if (!map[word[i]]) {
      map[word[i]] = counter
      counter++
    }
    output.push(map[word[i]])
  }
    
  return output 
}

如果您使用的是足够现代的 javascript 版本 (es6),您还可以使用 for..of 循环字符串:

const wordPattern = word => {
  word = word.toLowerCase();
  const map = {}
  const output = []
  let counter = 0
  
  for(const l of word) {
    if (!map[l]) {
      map[l] = counter
      counter++
    }
    output.push(map[l])
  }
  return output 
}

【讨论】:

  • 非常感谢!映射是个好办法,没想到!
【解决方案2】:

您可以使用常规 if 语句在循环中向前看

const wordPattern = word => {
  word = word.toLowerCase();
  let index =[];
  // Because you don't want word letters index,
  // you can create separate index
  let c = 0;
  
  for(let i=0; i<word.length; i++){
    // Add c to index array
    index.push(c);
    // Increase c index
    c++;
    // Look ahead and do simple logic
    // by decreasing your c index if next
    // letter equals current
    if(word[i+1] && word[i+1] === word[i]) c--;
  }
    
  return index 
}

// Test
console.log(wordPattern('Hello').toString());
console.log(wordPattern('Success').toString());

【讨论】:

  • 谢谢塔克!这样说起来真的很简单!感谢时间和解释:)
  • 欢迎!如果回答对您有帮助,请在设置中接受;)
猜你喜欢
  • 1970-01-01
  • 2021-05-07
  • 2013-10-02
  • 2020-03-29
  • 1970-01-01
  • 2021-06-15
  • 2014-01-31
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多