算法学习(一) - Javascript实现

算法学习(一) - Javascript实现

[toc]

参考学习目录:https://github.com/nonstriater/Learn-Algorithms

字符串处理

单词反转

1
2
3
4
5
6
7
8
function WordReversal() {
let word = "abcd1234";
let newWord = "";
for (let i in word) {
newWord = word[i] + newWord;
}
console.log(word, newWord); // 4321dcba
}

回文判断

1
2
3
4
5
6
7
8
9
10
11
function CheckPalindrome() {
let test = "1234321";
let isIt = true;
for (let i in test) {
if (test[i] != test[test.length - i - 1]) {
isIt = false;
break;
}
}
console.log(test, isIt); // true
}

字符串压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function CompressWord() {
let word = "aaassddffgggg";
let out = "";
let ch = word[0];
let count = 0;
for (let i in word) {
if (word[i] == ch && i != word.length - 1) {
count++;
} else {
out += ch + count;
ch = word[i];
count = 1;
}
}
// 怪方法?
console.log(word, out.substring(0, out.length - 1) + eval(`${[...out][out.length - 1]} + 1`)); // a3s2d2f2g4
}

字符串排列组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function WordPermutationAndCombination() {
let word = "yes";
function permutation(_array, _begin) {
if (_begin == _array.length - 1) {
console.log(_array.join('')); // yse eys esy sey sye
} else {
for (let i = _begin; i < _array.length; i++) {
[_array[_begin], _array[i]] = [_array[i], _array[_begin]];
permutation(_array, _begin + 1);
[_array[i], _array[_begin]] = [_array[_begin], _array[i]];
}
}
}
permutation([...word], 0);
}

字符串比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function WordCompare() {
let word1 = "hello";
let word2 = "hello";
let len1 = word1.length;
let len2 = word2.length;
let ret = true
if (len1 != len2) {
ret = false;
console.log(`${word1} and ${word2} is ${ret}`);
} else {
for (let i = 0; i < len1 / 2 + 1; i++) {
if (word1[i] != word2[i] || word1[len1 - i - 1] != word2[len2 - i - 1]) {
ret = false;
break;
}
}
console.log(`${word1} and ${word2} is ${ret}`); // true
}
}

字符串子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function SubWord() {
let word1 = "good morning, good evening.";
let word2 = "good";
let len1 = word1.length;
let len2 = word2.length;
let index = [];
cmp = (i) => {
let ret = true;
for (let j = 0; j < len2; j++) {
console.log(word1[i], word2[j])
if (word1[i] != word2[j]) {
ret = false;
return ret;
break;
} else {
i++;
}
}
return ret;
}
for (let i = 0; i < len1 - len2; i++) {
if (cmp(i)) {
index.push(i);
}
}
console.log("子串的位置:", index); // [0, 14]
}
还在学习中,持续更新...
当然也欢迎大佬提出更优解法!
打赏
  • 版权声明: 本博客采用 Apache License 2.0 许可协议。
    转载请注明出处: https://ryzenx.com/2021/03/algorithm-js-1/

请我喝杯咖啡吧~

支付宝
微信