庞果网在线编程之最长有效括号长度问题ruby解答

来源:互联网 发布:c socket 端口复用 编辑:程序博客网 时间:2024/04/30 06:11

题目地址:http://hero.pongo.cn/OnlineCompiler/Index?ID=54&ExamID=52


题目详情:

给定只包含括号字符'('和 ')''的字符串,请找出最长的有效括号内子括号的长度。


举几个例子如下:

  1. 例如对于"( ()",最长的有效的括号中的子字符串是"()" ,有效双括号数1个,故它的长度为 2。 
  2. 再比如对于字符串") () () )",其中最长的有效的括号中的子字符串是"() ()",有效双括号数2个,故它的长度为4。 
  3. 再比如对于"( () () )",它的长度为6。     

    换言之,便是有效双括号"()"数的两倍。

给定函数原型int longestValidParentheses(string s),请完成此函数,实现上述功能。


这道题目有些太小儿科了,凡是大学学过stack概念的人都应该直接就找到解题的方向吧。


class BracketString  def initialize(string)    @brackets = string.chars.to_a  end  def longest_valid_parentheses    stack = []    match_count = 0    @brackets.each do |char|       if stack.last == '(' and char == ')'         stack.pop         match_count += 1       else         stack.push char       end    end    match_count * 2  endenddescribe BracketString do  it "should return 2 if input is (() " do     BracketString.new("(()").longest_valid_parentheses.should == 2  end  it "should return 4 if input is ) () () )" do    BracketString.new(")()())").longest_valid_parentheses.should == 4  end  it "should return 6 if input is ( () () ) " do     BracketString.new("(()())").longest_valid_parentheses.should == 6  endend


原创粉丝点击