<script setup lang="ts">
import { ref } from 'vue';
const input = ref('')
const resoult = ref('')
const btnClick = () => {
//初始化
resoult.value = ''
const str: string = input.value
const arr: Array<string> = []
//字符串长度为0或者未匹配到目标值’[‘,直接返回false
if (str?.length === 0 || str.indexOf('[') === -1) {
resoult.value = 'false'
return
}
//循环便利字符串
for (let index = 0; index < str.length; index++) {
//匹配到目标值后,向数组中压入目标值
if (str.charAt(index) === '[') {
arr.push(str.charAt(index))
} else if (str.charAt(index) === ']') {
//当匹配到目标值配对的字符串后,分情况判断
//1、当数组长度为0时,说明字符串中,中括号的前后顺序不对
if (arr?.length === 0) {
resoult.value = 'false'
return
} else {
//2、说明中括号匹配上了,数组中抵消一个’[‘
arr.pop()
}
}
}
//遍历结束后,判断数组长度
//若数组长度为0,则字符串中中括号成对出现
if (arr?.length === 0) {
resoult.value = 'true'
} else {
//否则,字符串中还有未闭合的中括号
resoult.value = 'false'
}
}
</script>