[英]How do I compact contiguous repeated elements in a string in C?
我的問題的一個例子:
輸入:“abcabcabcabcxyxyxyccccccc”
output:“abc4xy3c7”
到目前為止,我已經編寫了一個代碼,可以計算字符串中的所有字符並將這些數字存儲到一個從 0 到 25 的數組中,它代表字母表(我只考慮小寫字母)。 對於上面的示例,我的代碼將生成以下數組:
letter_count = [4 4 4 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 0]
由此,我將能夠知道哪些子字符串是哪些子字符串並相應地打印它們。 但無論如何我都做不到。
有人可以幫助我嗎?
更新:刪除轉換為數組的步驟
我假設你從一個字符串開始,所以......
第一個初始化一個空的輔助數組,它將保存結果
下一次像數組一樣循環遍歷字符串,詢問當前元素是否與結果數組中的最后一個元素相同,如果不是,則將當前元素添加到輔助數組,否則繼續下一個元素。
這應該給你你正在尋找的東西。
這聽起來有點家庭作業,所以我將把我的想法寫在這里。 letter_count 數組在這里沒有值。 我認為使用的方法是: -
startindex = 0
while startindex < length of string
for n = 1 to (length of string - startindex) / 2
if substring (startindex, n) == substring (startindex+n, n) then
found a repitition, count how many times substring is repeated
output substring and repitition count
set startindex to index of last character in repeated string
break
startindex = startindex + 1
缺少一些東西(例如,如果您發現像 abcdcd 這樣的非重復序列),但我想這是一個開始。
思考問題,ababcdababcd 的 output 會是什么? 是 ab2cd1ab2cd1 還是 ababcd2? 算法是否應該找到最短的壓縮字符串?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.