Skip to content

Commit ddd9357

Browse files
committed
Merge branch 'answers/chapter-1' of https://github.com/targunp/CtCI-6th-Edition-JavaScript into targunp-answers/chapter-1
2 parents 1032f5c + 5cd567f commit ddd9357

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module.exports = Strings1_4 = (function() {
2+
return{
3+
// Checks if a string is a permutation of a palindrome
4+
// Solution #4 from the book. Assumes ascii character set
5+
// @param {String} str - Word or phrase
6+
// @retuns {Boolean} - true if a permutation of palindrome exists, false if it does not
7+
palindromePermutation: function(str){
8+
var distinct = 0;
9+
var s_array = Array.apply(null, Array(256)).map(Number.prototype.valueOf, 0);
10+
str = str.toLowerCase();
11+
for(var i = 0; i < str.length; i++){
12+
if(str[i] == ' '){
13+
continue;
14+
}
15+
s_array[str[i].charCodeAt(0)]++;
16+
if(s_array[str[i].charCodeAt(0)] % 2){
17+
distinct++;
18+
}else{
19+
distinct--;
20+
}
21+
}
22+
return (distinct < 2);
23+
}
24+
}
25+
}());
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
require('../../test_helper');
2+
describe('1.4 #palindromePermutation', function () {
3+
it('returns true if a string is a permutation of a palindrom', function () {
4+
expect(Strings1_4.palindromePermutation('Tact Coa')).to.be.true;
5+
expect(Strings1_4.palindromePermutation('jhsabckuj ahjsbckj')).to.be.true;
6+
expect(Strings1_4.palindromePermutation('Able was I ere I saw Elba')).to.be.true;
7+
});
8+
it('returns false if a string is not a permutation of a palindrome', function () {
9+
expect(Strings1_4.palindromePermutation('So patient a nurse to nurse a patient so')).to.be.false;
10+
expect(Strings1_4.palindromePermutation('Random Words')).to.be.false;
11+
expect(Strings1_4.palindromePermutation('Not a Palindrome')).to.be.false;
12+
});
13+
});

0 commit comments

Comments
 (0)