正則表達式平衡組解決括號表達式的面試問題

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetMax(")()(()())("));

            Console.Read();
        }

        static int GetMax(String str)
        {
            Regex regex = new Regex("((?<open>\\()|(?<-open>\\)))*(?(open)(?!))");
            var matches = regex.Matches(str);
            return matches.OfType<Match>().Max(m => m.Length);
        }
    }

當然,使用雙層for循環也可以解決,但沒有平衡組匹配解決的簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章