環控制應該使用陣列的範圍的大小,和a[i + 1]
索引可以是出界如果i
是索引到最後一個元件,因此,使用a[i - 1]
代替並遍歷範圍[1
.. sizeof(a)/sizeof(a[0])
]優選
該算法最好使用3個變量解決:
char* last
點的連續字符當前字符串的第一個元素
int count1
連續對在當前計數
int count
記錄連續對
該算法的最高數目的數目最好使用一個狀態機示出。它將運行於:
- 在進入設置
last
到NULL
,如果count1
大於count
分配count1
到count
,並重置count1
到0
- 在進入設置
last
到的第一個字符在這串連續的字符中(a[i-1]
)
- 一旦輸入就添加連續字符的個數RS指向最後除以2,以僅發現對
這是糾正代碼註釋內聯:
size_t i = 0;
char* last = NULL;
long int count1 = 0;
long int count = 0;
char a[] = {'d', 'p', 'p', 'c', 'c', 'd', 'd', 'd'};
while (++i < sizeof(a)/sizeof(a[0])) { // This will iterate over the range: [1 .. sizeof(a)/sizeof(a[0])]
if (a[i - 1] == a[i]) { // Test previous character to avoid going out of range
if (last == NULL) { // Entry to state 2
last = a + i - 1;
}
} else if (last != NULL) {
if (a + i - last > 1) { // Entry to state 3
count1 += (a + i - last)/2;
last = a + i;
} else { // Entry to state 1
if (count1 > count) { // If the current count is larger
count = count1; // Replace the maximum count
}
count1 = 0; // Reset the current count
last = NULL;
}
}
}
if (last != NULL) { // Entry to state 3
if (a + (sizeof(a)/sizeof(a[0])) - last > 1) {
count1 += (a + (sizeof(a)/sizeof(a[0])) - last)/2;
}
if (count1 > count) { // If the current count is larger
count = count1; // Replace the maximum count
}
}
printf("%ld", count);
[Live Example]
你宣佈** **我作爲int,但是你將它與未定義的(sizeof)進行比較,然後** count **被聲明爲int並且在這裏** count1 + =(a + i - last)/ 2; **錯誤:從'long int'轉換爲'int'可能會改變其值** – Michi
@Michi有趣的是,這將有助於轉換在64位機器上失敗。我想http://www.ideone.com必須仍然是32位,因爲我沒有任何問題。無論哪種情況,我相信我已經修好了,謝謝你的提示。 –
UpONE的方式如何解釋它,現在編譯好。 – Michi