与字符串相关的常见算法

字符串逆序输出

1
2
3
4
5
6
7
8
/*
* @Description: reverseString
* @Author: libk
* @Github: <https://github.com/libk>
*/
function reverseString (str) {
return str.split('').reverse().join('')
}

统计字符串中出现最多的字符及出现的次数

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
/*
* @Description: 统计字符串中出现最多的字符及出现的次数,出现次数最多的字符只有一个
* @Author: libk
* @Github: <https://github.com/libk>
*/
function getMaxCount (str) {
const hashTable = {}
for (let i = 0; i < str.length; i++) {
if (hashTable[str[i]] === undefined) {
hashTable[str[i]] = 1
} else {
hashTable[str[i]]++
}
}

let maxCount = 0
let maxChar = ''

for (let i in hashTable) {
if (hashTable[i] > maxCount) {
maxCount = hashTable[i]
maxChar = i
}
}
return `字符${maxChar}出现次数最多,出现了${maxCount}次`
}

去除字符串中重复的字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @Description: 字符串去重
* @Author: libk
* @Github: <https://github.com/libk>
*/
function removeDupChar (str) {
const hashTable = {}
let result = ''
for (let i = 0; i < str.length; i++) {
if (hashTable[str[i]] === undefined) {
hashTable[str[i]] = true
result += str[i]
}
}
return result
}

判断一个字符串是否为回文字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
* @Description: 判断字符串是否为回文字符串,不区分大小写
* @Author: libk
* @Github: https://github.com/libk
*/
function isPalStr (str) {
let start = 0
let end = str.length - 1
while (start < end) {
if (str[start] === str[end]) {
start++
end--
} else {
return false
}
}
return true
}