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 `)´


沒有留言:

張貼留言

Basic Blind Chess的兩大問題

 Basic Blind Chess已經好久沒更新了, Windows版可以獲得最好的遊戲体驗, 但是Android版的,不只是比較舊, 它其實存在兩大問題: 1. 拿子移動時,顯示怪怪的,只顯示前幾個移動的殘影。 這個只有在最早的版本,沒有這個問題, 但是最早的版本實機測試時,...