2012-07-27 100 views
1

我需要編寫一個函數,它接受一個字符串並返回它在Lua中刪除重複字符。我需要什麼幫助是...在字符串中重複

  • 使字母和計數
  • 使每個字母等於只有一個散列,刪除出現了多次
  • 哈希轉換到新的字符串複製刪除

一個簡單的函數/算法將不勝感激!

回答

4

如果您只需要每個字符的一個實例,那麼您可能不需要跟蹤計數;您可以將輸入字符串與用於生成輸出的同一個表進行比較。

local function contains(tbl, val) 
    for k,v in pairs(tbl) do 
    if v == val then return true end 
    end 
    return false 
end 

local function uniq(str) 
    local out = {} 
    for s in str:gmatch(".") do 
    if not contains(out, s) then out[#out+1] = s end 
    end 
    return table.concat(out) 
end 

print(uniq("the quick brown fox jumps over the lazy dog")) 
-- the quickbrownfxjmpsvlazydg 

這可能比下面的功能短字符串慢,但它通常最好避免過度的字符串連接在Lua,理由概括here。如果你確定輸出字符串將是相當短的,你可以擺脫並使用此:

local function uniq(str) 
    local out = "" 
    for s in str:gmatch(".") do 
    if not out:find(s) then out = out .. s end 
    end 
    return out 
end 
+0

我用了較短的,它完美!非常感謝你,我非常感謝你的幫助。完美解決方案 – 2012-07-27 04:59:37