Klay's Notebook

阿胡的的流水账


  • Home
  • Archive
  • Categories
  • Tags
  •   

© 2026 Klay-Clam

Theme Typography by Makito

Proudly published with Hexo

CodeWars 学习记录(二)

Posted at 2020-01-03 JavaScript  JavaScript 

CamelCase Method

Write simple .camelCase method (camel_case function in PHP, CamelCase in C# or camelCase in Java) for strings. All words must have their first letter capitalized without spaces.

For instance:

1
2
"hello case".camelCase() => HelloCase
"camel case word".camelCase() => CamelCaseWord

解法

  1. 我自己的解法
1
2
3
4
5
6
String.prototype.camelCase = function () {
let uw = this.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
});
return uw.replace(" ", "");
};
  1. 看到的更加巧妙的解法
1
2
3
4
5
6
7
8
9
10
String.prototype.camelCase = function () {
const capitalize = (word) => {
return word.slice(0, 1).toUpperCase() + word.slice(1);
};

return this
.split(" ")
.map(capitalize)
.join("");
};

Format a string of names like ‘Bart, Lisa & Maggie’

Given: an array containing hashes of names.

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example:

1
2
3
4
5
6
7
8
9
10
11
list([{name: "Bart"}, {name: "Lisa"}, {name: "Maggie"}])
// returns "Bart, Lisa & Maggie"

list([{name: "Bart"}, {name: "Lisa"}])
// returns "Bart & Lisa"

list([{name: "Bart"}])
// returns "Bart"

list([])
// returns ""

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function list(names) {
return names.formatName();
}

Array.prototype.formatName = function () {
let result = "";
this.forEach((item, index) => {
if (index === 0) {
result = item.name;
} else if (index === this.length - 1) {
result = `${result} & ${item.name}`;
} else {
result = `${result}, ${item.name}`;
}
});

return result;
};

scramble

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:

  • Only lower case letters will be used (a-z).
  • Performance needs to be considered.

Examples:

1
2
3
scramble("rkqodlw", "world") ==> true
scramble("cedewaraaossoqqyt", "codewars") ==> true
scramble("katas", "steak") ==> false

我的解法

1
2
3
4
5
6
7
8
9
10
11
function scramble(str1, str2) {
var count = Object.create(null);

Array.prototype.forEach.call(str1, function (a) {
count[a] = (count[a] || 0) + 1;
});

return Array.prototype.every.call(str2, function (a) {
return count[a]--;
});
}

最开始的时候我用了 indexOf 来查找 str1 是否存在 str2 中的字符,跑测试的时候超时了。
果然还是效率太低了。构造对象之后,使用 key:value 的方式寻找效率更好。

Share 

 Next post: 2019:我这一年 

© 2026 Klay-Clam

Theme Typography by Makito

Proudly published with Hexo