2025年10月20日 星期一

Lua, 使用string:gsub("%b()", "")

7kyu, Valid Parentheses

 7kyu的題目,一樣不難。

是求Parentheses是否balanced?

我採用最基本的解法,如下:
local function valid_parentheses(paren_str)
  local s = 0
  for i = 1, #paren_str do
    local p = paren_str:sub(i, i)
    if ")" == p then
      s = s - 1
    elseif "(" == p then
      s = s + 1
    end
    if s < 0 then
      return false
    end
  end
  if 0 == s then
    return true
  else
    return false
  end
end

return valid_parentheses

別人是用string:gsub("%b()", "")來解,滿精簡的:

local function valid_parentheses(paren_str)
  return paren_str:gsub("%b()", "") == ""
end

return valid_parentheses

Note:

a pattern is the '%b', that matches balanced strings. Such item is written as '%bxy', where x and y are any two distinct characters; the x acts as an opening character and the y as the closing one. For instance, the pattern '%b()' matches parts of the string that start with a `(´ and finish at the respective `)´


沒有留言:

張貼留言

Lua, 使用string:gsub("%b()", "")

7kyu, Valid Parentheses  7kyu的題目,一樣不難。 是求Parentheses是否balanced? 我採用最基本的解法,如下: local function valid_parentheses ( paren_str ) local s =...