資料結構與演算法之Stack(棧)的應用——in dart
阿新 • • 發佈:2019-01-12
參考教科書上的一個應用例子,用棧來分析一行輸入中的括號brackets是否匹配。用stdin讀取使用者輸入,並輸出檢查結果。exit 退出。
注意這行程式碼:
import 'stack.dart';
// 需要與上一個Stack的例子在同一個資料夾下。
1 import 'dart:io'; 2 import 'stack.dart'; 3 4 void main() { 5 var ins = stdin.readLineSync(); 6 while (ins != 'exit') { 7 print(check(ins)); 8 ins = stdin.readLineSync();9 } 10 } 11 12 bool check(String ins) { 13 var stack = Stack<String>(ins.length); 14 for (var i = 0; i < ins.length; i++) { 15 switch (ins[i]) { 16 case '{': 17 case '[': 18 case '(': 19 stack.push(ins[i]); 20 break; 21 case ')': 22 if(stack.isEmpty || stack.pop() != '(') return false; 23 break; 24 case ']': 25 if (stack.isEmpty || stack.pop() != '[') return false; 26 break; 27 case '}': 28 if (stack.isEmpty || stack.pop() != '{') return false; 29 break; 30 default: 31 break; 32 } 33 } 34 return stack.isEmpty; 35 }