2025年10月15日 星期三

7 kyu: Ordered Count of Characters using Lua

 7 kyu: Ordered Count of Characters

這題很簡單,要做的只是計算string中各字元出現的次數。
我一開始寫的code如下:
local solution = {}

function solution.ordered_count(inp)
  local a, aa, orderkey = {}, {}, {}
  for i = 1, #inp do
    local c = inp:sub(i, i)
    if nil == a[c] then
      a[c] = 1
      table.insert(orderkey, c)
    else
      a[c] = a[c] + 1
    end
  end
  for i, v in ipairs(orderkey) do
    table.insert(aa, {orderkey[i], a[orderkey[i]]})
  end
  return  aa
end

return solution

後來看了別人的寫法後,
發現可以寫的更精簡一點,
只要宣告兩個table結構即可。
一個table aa存答案,
一個table a, key存字元,value存table aa的index.
改寫如下:
local solution = {}

function solution.ordered_count(inp)
  local a, aa = {}, {}
  for i = 1, #inp do
    local c = inp:sub(i, i)
    if nil == a[c] then
      table.insert(aa, {c, 1})
      a[c] = #aa
    else
      aa[a[c]][2] = aa[a[c]][2] + 1
    end
  end
  return  aa
end

return solution

沒有留言:

張貼留言

7 kyu: Ordered Count of Characters using Lua

 7 kyu: Ordered Count of Characters 這題很簡單,要做的只是計算string中各字元出現的次數。 我一開始寫的code如下: local solution = {} function solution.ordered_count ( in...