English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

二、括號配對
在本題中,題目會先給你一個包含小號( )及中括號[ ]的字串。當字串符合下列條件時我們稱它為正確的運算式:
1.該字串為一個空字串。
2.如果A為正確的運算式,則(A)及[A]都為正確的運算式。
3.如果A和B都為正確的運算式,則AB也為正確的運算式。

現在,請你寫一個程式,可以讀入這類字串,並檢查它們是否為正確的運算式。字串的最大長度為128個字元。

輸入規範
輸入檔案的第一列為正整數 n,表接下來有n個列待測資料。

輸出規範
檢查每列待測資料,如果正確輸出YES,否則輸出NO。

輸入範例(test2.txt)
3
([])
(([()])))
([()[]()])()

輸出範例(resul2.txt)
YES
NO
YES


煩請大大解答,詳者得。
小妹我會感謝不已的! 快被逼瘋了 冏"

2007-03-11 17:32:17 · 2 個解答 · 發問者 Count 1 in 電腦與網際網路 程式設計

2 個解答


'不知道有沒有Bug
圖片參考:http://tw.yimg.com/i/tw/blog/smiley/9.gif
請把+\改成半型
Private Sub Command1_Click()
Dim I As Integer, N As String, S As String, A As String
Open "C:\Test2.txt" For Input As #1
Line Input #1, N
For I = 1 To N
  Line Input #1, S
  A = A & Test(S) & vbCrLf
Next
Close #1
Open "C:\resul2.txt" For Output As #1
Print #1, Left(A, Len(A) - 1)
Close #1
End Sub
Function Test(ByVal S As String) As String
Dim I As Integer, N As Integer
Test = "NO"
N = Len(S)
If N < 2 And N > 128 Then Exit Function
If N Mod 2 Then Exit Function
If Mid(S, 1, 1) = ")" Or Mid(S, 1, 1) = "]" Or Mid(S, N) = "(" Or Mid(S, N) = "[" Then Exit Function
If UBound(Split(S, "(")) <> UBound(Split(S, ")")) Then Exit Function
If UBound(Split(S, "[")) <> UBound(Split(S, "]")) Then Exit Function
For I = 1 To N - 1
  Select Case Mid(S, I, 1)
    Case "[": If Mid(S, I+ 1, 1) = ")" Then Exit Function
    Case "(": If Mid(S, I+ 1, 1) = "]" Then Exit Function
  End Select
Next
Test = "YES"
End Function

2007-03-11 20:45:34 · answer #1 · answered by W.J.S. 7 · 0 0

這一題只是單純考stack的應用
而且還是ACM的題目...XD

2007-03-11 18:58:15 · answer #2 · answered by ? 4 · 0 0

fedest.com, questions and answers