2015-09-22 78 views
1

給定一個任意char[]查找字符串中字符對的數量。所以這將是3:查找列表中重複的對數

aabbcc

如果應該計數兩對相鄰的兩個字符相同的字符。因此,這將是3:

aaaabb

所述的中斷單char必須重置連續字符對的計數。因此,這將是1:

aabcc

如果中斷單個字符是相同的前面的一對它復位連續字符對計數。因此,這將是3:

aabbbccc


這是this question適應。對這個問題的最初解釋很有意思,但是這些評論不斷改變了這個問題的本質,從原來的解釋。 This was my answer到原來的解釋,我想知道是否可以改進?

回答

1

環控制應該使用陣列的範圍的大小,和a[i + 1]索引可以是出界如果i是索引到最後一個元件,因此,使用a[i - 1]代替並遍歷範圍[1 .. sizeof(a)/sizeof(a[0]) ]優選

該算法最好使用3個變量解決:

  • char* last點的連續字符當前字符串的第一個元素
  • int count1連續對在當前計數
  • int count記錄連續對

該算法的最高數目的數目最好使用一個狀態機示出。它將運行於:

State Machine

  1. 在進入設置lastNULL,如果count1大於count分配count1count,並重置count10
  2. 在進入設置last到的第一個字符在這串連續的字符中(a[i-1]
  3. 一旦輸入就添加連續字符的個數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]

+1

你宣佈** **我作爲int,但是你將它與未定義的(sizeof)進行比較,然後** count **被聲明爲int並且在這裏** count1 + =(a + i - last)/ 2; **錯誤:從'long int'轉換爲'int'可能會改變其值** – Michi

+0

@Michi有趣的是,這將有助於轉換在64位機器上失敗。我想http://www.ideone.com必須仍然是32位,因爲我沒有任何問題。無論哪種情況,我相信我已經修好了,謝謝你的提示。 –

+1

UpONE的方式如何解釋它,現在編譯好。 – Michi