javascript高级思想
1.案例1----指针思想
将下面的字符串找出连续且重复次数最多的字母
比如 aaaaaabbbbbbbcccccccccccccddddd 结果就是c 次数是13次
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Guiding Ideology</title>
</head>
<body>
<script type="text/javascript">
//Find the most consecutive and repeated characters in the string
let str = "aaaaaabbbbbbbcccccccccccccddddd"
//Pointer
let i = 0
let j = 1
//The most repeated and frequently used letter
let maxRepeat = 0
let maxLetter = ""
while (i <= str.length - 1) {
if (str[i] !== str[j]) {
if (j - i > maxRepeat) {
maxRepeat = j - i
maxLetter = str[i]
}
i = j
}
j++
}
console.log(`The most repeated is ${maxRepeat},and frequently used letter is ${maxLetter}`)
</script>
</body>
</html>
2.案例2----深入递归
利用递归输出斐波那契数列前10项,但是我们的递归计算太密集也就是计算量太大
但计算次数太多,我们利用缓存思想来解决递归计算数量庞大
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Deep Recursion One</title>
</head>
<body>
<script type="text/javascript">
//Output the top 10 items of Fibonacci number series by recursion
//Using cache idea to solve redundant and redundant computation
let cache = {}
//Define counters
let counter = 0
function fib(n) {
if (cache.hasOwnProperty(n)) {
counter++
return cache[n]
}
//Calculate the cache object and store it in the cache object
let cacheObject = n === 0 || n === 1 ? 1 : fib(n - 1) + fib(n - 2)
cache[n] = cacheObject
return cacheObject
}
for (let i = 0; i <= 9; i++) {
console.log(fib(i))
}
console.log(`Hit cache (no calculation required),And hit cache ${counter} second`)
</script>
</body>
</html>
3.案例3—递归与映射
将高维数组转化为类似虚拟dom的样式
[1, 2, [3, 4, [5]]]
{
{value:1}
{value:2}
{children:[
{value:3}
{value:4}
{children:[
{value:5}
]
}
]
}
}
由图将数组转化为那个形式
方法一 普通递归
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Deep Recursion Two</title>
</head>
<body>
<script type="text/javascript">
//Transform high-dimensional arrays into virtual DOM like models
let arr = [1, 2, 3, [4, 5, [6, 7, 8, [9, 10, 11]]]]
//Circulation method
function convert(arr) {
let resultArr = []
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number") {
resultArr.push({
value: arr[i]
})
} else if (Array.isArray(arr[i])) {
resultArr.push({
children: convert(arr[i])
})
}
}
return resultArr
}
let result = convert(arr)
console.log(result)
</script>
</body>
</html>
这样写虽然可以解决问题,但利用了循环判断,这时我们可以优化一下
利用es6新增的map方法进行映射,实现反复递归调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Deep Recursion Three</title>
</head>
<body>
<script type="text/javascript">
//Transform high-dimensional arrays into virtual DOM like models
let arr = [1, 2, 3, [4, 5, [6, 7, 8, [9, 10, 11]]]]
//By mapping method
function convert(item) {
if (typeof item === "number") {
return {
value: item
}
} else if (Array.isArray(item)) {
return {
children: item.map(_item => convert(_item))
}
}
}
let result = convert(arr)
console.log(result)
</script>
</body>
</html>
4.案例4—栈与正则表达式
在前端中一般与数据结构的接触不会太多,但在框架的底层例如Vue,大多数都能看到栈的身影,案例:
将字符串3[2[a]2[b]] ===>> aabbaabbaabb
将字串3[2[abc]2[ddd]] ===>> abcabcddddddabcabcddddddabcabcdddddd
思路:进行正则匹配与栈结合,匹配成功进行入栈或弹栈,最后拼接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stack Algorithm One</title>
</head>
<body>
<script type="text/javascript">
//Using the idea of stack to solve the problem that can only be repeated
//for example:
//3[2[a]2[b]] ===>> aabbaabbaabb and 3[2[a]2[b]] is a String
let templateString = "3[2[abc]2[ddd]]"
function smartRepeat(templateString) {
if (typeof templateString !== "string") {
throw new Error("Please enter a value of type string")
}
let index = 0
let stackNumber = []
let stackTemporaryString = []
let remainingString = templateString
while (index < templateString.length - 1) {
//Repeatedly replace the remaining strings
remainingString = templateString.substring(index)
//Use regular expressions to determine
//If the remaining string starts with a number and "[",
// we stack the number and stack the empty string
if (/^\d+\[/.test(remainingString)) {
let times = Number(remainingString.match(/^(\d+)\[/)[1])
stackNumber.push(times)
stackTemporaryString.push("")
index += times.toString().length + 1
}
//If the remaining string starts with letters and "]",
// we replace the empty string of the previous item with letters
else if (/^\w+]/.test(remainingString)) {
let words = remainingString.match(/^(\w+)]/)[1]
stackTemporaryString[stackTemporaryString.length - 1] = words
index += words.length
}
//Finally, if it ends with "]" , we double stack the number stack and the character stack,
//and generate multiple strings and then concatenate with the stack on the character stack
else if (remainingString[0] === ']') {
let number = stackNumber.pop()
let word = stackTemporaryString.pop()
stackTemporaryString[stackTemporaryString.length - 1] +=
word.repeat(number)
index++
}
}
//The return value of the function is a multifold concatenation
//of the last remaining items in the two stacks
return stackTemporaryString[0].repeat(stackNumber[0])
}
let result = smartRepeat(templateString)
console.log(result)
</script>
</body>
</html>