jijixi #4300(2007/11/21 19:03 GMT) [ Ruby ] Rating1/1=1.00
副作用無しで
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
$KCODE = 'u' PARENS = { '(' => ')', '{' => '}', '[' => ']', } RPARENS = PARENS.invert def reverseString2_(str, acc, paren) if str.empty? [acc, []] else ch, *rest = str if PARENS.keys.include?(ch) str_, rest_ = reverseString2_(rest, [], ch) ch_ = if str_.first == ch PARENS[ch] else ch end reverseString2_(rest_, [str_, ch_, acc], paren) elsif paren and RPARENS.keys.include?(ch) ch_ = if ch == PARENS[paren] RPARENS[ch] else ch end [[ch_, acc], rest] else reverseString2_(rest, [ch, acc], paren) end end end def reverseString2(str) str_ = str.split(//) reversed, _ = reverseString2_(str_, [], nil) reversed.flatten.join end SAMPLE = [ ["文字列(もじれつ)の反転(はんてん)", "(んてんは)転反の(つれじも)列字文"], ["対応[の{とれている(さまざまな)括弧}の(例)]です。", "。すで[(例)の{弧括(なまざまさ)るいてれと}の]応対"], ["これ(は(対応のとれていない)括弧がある例です。", "。すで例るあが弧括(いないてれとの応対)は(れこ"], ["これ(も{対応の)とれていない}括弧の例です。", "。すで例の弧括}いないてれと)の応対{も(れこ"], ] def test_reverseString2 SAMPLE.each do |input,expected| cond = if expected == (result = reverseString2(input)) then :OK else :NG end puts "reverseString2(#{input.inspect})" puts " expected: #{expected.inspect}" print " result: #{result.inspect}" puts " ... #{cond}" end end if __FILE__ == $0 then test_reverseString2() end
Rating1/1=1.00-0+
[ reply ]
jijixi
#4300()
[
Ruby
]
Rating1/1=1.00
副作用無しで
Rating1/1=1.00-0+
[ reply ]