File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change @@ -400,6 +400,27 @@ bool isValid(char * s){
400
400
return !stackTop;
401
401
}
402
402
```
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
+ ```
404
425
-----------------------
405
426
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
Original file line number Diff line number Diff line change @@ -374,6 +374,27 @@ func removeDuplicates(_ s: String) -> String {
374
374
return String (stack)
375
375
}
376
376
```
377
-
377
+ Scala:
378
+ ``` scala
379
+ object Solution {
380
+ import scala .collection .mutable
381
+ def removeDuplicates (s : String ): String = {
382
+ var stack = mutable.Stack [Int ]()
383
+ var str = " " // 保存最终结果
384
+ for (i <- s.indices) {
385
+ var tmp = s(i)
386
+ // 如果栈非空并且栈顶元素等于当前字符,那么删掉栈顶和字符串最后一个元素
387
+ if (! stack.isEmpty && tmp == stack.head) {
388
+ str = str.take(str.length - 1 )
389
+ stack.pop()
390
+ } else {
391
+ stack.push(tmp)
392
+ str += tmp
393
+ }
394
+ }
395
+ str
396
+ }
397
+ }
398
+ ```
378
399
-----------------------
379
400
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments