2010-01-04 144 views
1

我想解決以下問題,但無法找到一個優雅的解決方案。有任何想法嗎? 謝謝。乾淨的解決方案,以字符串內計數

輸入 - 可變長度的數字串,例如 string str =「5557476374202110373551116201」;

任務 - 檢查(從左到右)每個數字(忽略重複)都不會出現在以下兩個索引中。使用例如。以上,第一個數字= 5。忽略代表,我們看到組中的最後一個索引爲5,因此我們檢查後面的2個索引,即3和4不應該有5個。如果這樣做,我們將它算作錯誤。目標是計算字符串中的這些錯誤。

在上面的字符串錯誤是在指標,3,10和16

+0

等等,你只是說重複應該被忽略,那麼如何在索引3有錯誤? – Amber 2010-01-04 02:09:32

+3

呵呵?這是一個功課問題嗎? – 2010-01-04 02:09:51

+0

另外,如果位置3有5個,它是不是隻是組的一部分?這沒有任何意義。 – danben 2010-01-04 02:12:31

回答

5

除了其他優秀的解決方案,你可以使用一個簡單的正則表達式:

foreach (Match m in Regexp.Matches(str, @"(\d)(?!\1)(?=\d\1)")) 
    Console.WriteLine("Error: " + m.Index); 

回報3,10,16。這將使用向後引用的反向引用來匹配相鄰的錯誤。處理重複。 .net應該支持這一點。如果沒有,你可以使用一個非反向引用版本:

(?<=0[^0])0|(?<=1[^1])1|(?<=2[^2])2|(?<=3[^3])3|(?<=4[^4])4|(?<=5[^5])5|(?<=6[^6])6|(?<=7[^7])7|(?<=8[^8])8|(?<=9[^9])9

+0

+1非反向引用版本的Man-point。讓人驚訝。 – ProfK 2010-01-04 05:34:18

3

簡單的索引的for循環與一對夫婦向前看,如果檢查會工作的。您可以將字符串視爲char []或IEnumerable - 您可以使用該方法遍歷所有字符並執行前瞻檢查以查看以下一個或兩個字符是否重複。

2

對不起,不是C#的人,但在這裏是用Ruby一個簡單的解決方案:

a="5557476374202110373551116201" 
0.upto(a.length) do |i| 
    puts "error at #{i}" if a[i]!=a[i+1] && a[i]==a[i+2] 
end 

輸出:

error at 3 
error at 10 
error at 16 
1

這是我在C#中扔在一起的東西,它與來自問題的示例輸入一起工作。我沒有徹底檢查它,雖然...

public static IEnumerable<int> GetErrorIndices(string text) { 
    if (string.IsNullOrEmpty(text)) 
     yield break; 

    int i = 0; 
    while (i < text.Length) { 
     char c = text[i]; 

     // get the index of the next character that isn't a repetition 
     int nextIndex = i + 1; 
     while (nextIndex < text.Length && text[nextIndex] == c) 
      nextIndex++; 

     // if we've reached the end of the string, there's no error 
     if (nextIndex + 1 >= text.Length) 
      break; 

     // we actually only care about text[nextIndex + 1], 
     // NOT text[nextIndex] ... why? because text[nextIndex] 
     // CAN'T be a repetition (we already skipped to the first 
     // non-repetition) 
     if (text[nextIndex + 1] == c) 
      yield return i; 

     i = nextIndex; 
    } 

    yield break; 
} 
相關問題