2010-01-04 145 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; 
} 
相关问题