我似乎无法弄清楚如何从 Javascript 中的字符串生成波浪。
规则:
- 输入总是小写字符串。
- 忽略空格。
预期结果:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]
wave ("") => []
这是我得到的。当前代码将给我一个答案 ["hello", "hello", "hello", "hello", "hello"]
。我正在考虑使用第二个 for 循环并以某种方式将每个新字母大写,但我很困惑。另外,如果答案能避免在循环 O(n^2)
中使用循环,我将不胜感激。因为 BIG O 可扩展性。
const wave = (str) => {
if(typeof str === 'string' && str === str.toLowerCase()){
for (let index = 0; index < str.length; index++) {
array.push(str);
}
for (let index = 0; index < str.length; index++) {
console.log(array);
}
}else{
alert(`${str} is either not a string or not lowercase`);
}
}
wave("hello");
最佳答案
您可以采用外循环来访问字符,如果找到非空格字符,则在该位置创建一个包含大写字母的新字符串。
function wave(string) {
var result = [],
i;
for (i = 0; i < string.length; i++) {
if (string[i] === ' ') continue;
result.push(Array.from(string, (c, j) => i === j ? c.toUpperCase() : c).join(''));
}
return result;
}
console.log(wave("hello")); // ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
console.log(wave(" h e y ")); // [" H e y ", " h E y ", " h e Y "]
console.log(wave("")); // []
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在 Javascript 中创建一波字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54983179/