[Codility] [7–1] Brackets (score 100%)

--

【Lesson 7–1】: Brackets 判斷字串裡是否有括號,需要注意對稱 (score 100%)

public static int Brackets(string S){if (S.Length == 0)return 1;if (S.Length > 200000)return 0;System.Collections.Generic.Stack<char> st = new System.Collections.Generic.Stack<char>();foreach (char ch in S.ToCharArray()){if (ch == '{' || ch == '[' || ch == '('){st.Push(ch);}else{if (st.Count == 0)return 0;char st_peek = st.Peek();if (st_peek == '{' && ch == '}')st.Pop();if (st_peek == '[' && ch == ']')st.Pop();if (st_peek == '(' && ch == ')')st.Pop();}}if (st.Count == 0)return 1;elsereturn 0;}

--

--

Charlie Chen (陳慶裕)
Charlie Chen (陳慶裕)

No responses yet