问题描述
我正在尝试解决一个非常简单的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
}
非常感谢!
解决方法
我将使用一个对象,因为它使我能够将键(字母)映射到值(分配给该字母的整数):
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
}
,
您可以使用常规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());