Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 61f5d92

Browse files
committed
添加 0020.有效的括号.md Scala版本
1 parent 98458cd commit 61f5d92

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

‎problems/0020.有效的括号.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,27 @@ bool isValid(char * s){
400400
return !stackTop;
401401
}
402402
```
403-
403+
Scala:
404+
```scala
405+
object Solution {
406+
import scala.collection.mutable
407+
def isValid(s: String): Boolean = {
408+
if(s.length % 2 != 0) return false // 如果字符串长度是奇数直接返回false
409+
val stack = mutable.Stack[Char]()
410+
// 循环遍历字符串
411+
for (i <- s.indices) {
412+
val c = s(i)
413+
if (c == '(' || c == '[' || c == '{') stack.push(c)
414+
else if(stack.isEmpty) return false // 如果没有(、[、{则直接返回false
415+
// 以下三种情况,不满足则直接返回false
416+
else if(c==')' && stack.pop() != '(') return false
417+
else if(c==']' && stack.pop() != '[') return false
418+
else if(c=='}' && stack.pop() != '{') return false
419+
}
420+
// 如果为空则正确匹配,否则还有余孽就不匹配
421+
stack.isEmpty
422+
}
423+
}
424+
```
404425
-----------------------
405426
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /