Skip to content

Commit d33b6da

Browse files
committed
[更改] 变更算法 722. 删除注释
1 parent eb37c45 commit d33b6da

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

src/722_removeComments.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ function removeComments (source: string[]): string[] {
7373

7474
// 初始化状态
7575
let charIndex = 0
76-
let isString = false
7776
let resultString = ''
7877

7978
// 遍历代码字符
@@ -82,11 +81,24 @@ function removeComments (source: string[]): string[] {
8281
const currentChar = sourceString[charIndex]
8382
const nextChar = sourceString[charIndex + 1]
8483

85-
// 1. 设置字符串状态
86-
if (currentChar === '"') isString = !isString
84+
// 1. 处理字符串
85+
if (currentChar === '"') {
86+
// 寻找下一个“"”
87+
const nextIndex = sourceString.indexOf('"', charIndex)
88+
// 找不到下一个“"”则说明直到代码结束都时该字符串也没有结束,将剩下的字符添加至 resultString,直接结束遍历
89+
if (nextIndex === -1) {
90+
resultString += sourceString.substring(charIndex, sourceString.length)
91+
break
92+
}
93+
// 将当前字符串代码添加至 resultString
94+
resultString += sourceString.substring(charIndex, nextIndex + 1)
95+
// 将字符索引设置为下一个“"”字符之后
96+
charIndex = nextIndex + 1
97+
continue
98+
}
8799

88100
// 2. 跳过单行注释(不为字符串时,判断当前字符与下一个字符的组合是否为“//”)
89-
if (!isString && (currentChar + nextChar === '//')) {
101+
if (currentChar + nextChar === '//') {
90102
// 寻找下一个换行符的位置
91103
const nextIndex = sourceString.indexOf('\n', charIndex)
92104
// 找不到下一个换行符则说明直到代码结束都不在有换行符,直接结束遍历
@@ -97,7 +109,7 @@ function removeComments (source: string[]): string[] {
97109
}
98110

99111
// 3. 跳过多行注释(不为字符串时,判断当前字符与下一个字符的组合是否为 “/*”)
100-
if (!isString && (currentChar + nextChar === '/*')) {
112+
if (currentChar + nextChar === '/*') {
101113
// 将字符索引设置为下一个 “*/” 之后,开始查找的索引为当前 “/*” 之后
102114
const nextIndex = sourceString.indexOf('*/', charIndex + 2)
103115
if (nextIndex === -1) break

0 commit comments

Comments
 (0)