找出“aa”的出现次数。在“caaab”中。 [英] Find the number of occurances of "aa" in "caaab".

查看:202
本文介绍了找出“aa”的出现次数。在“caaab”中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在caaab中查找aa的出现次数。

答案应为2.



我尝试过:



 string str = d; 
for(int number = 0; number< d.Length - genes [i] .Length; number ++)
{
var compstr = d.Substring(number,genes [i]。长度)的ToString();
str = d.Substring(1);
if(compstr == genes [i])
{
count ++;
}
}

解决方案

这是一个简单的问题,但我对简单优化感到惊讶人们会错过这样的问题。我们先来看一下代码:

  for  int  index =  0 ; index <  input.Length  -   1 ; index ++)
{
if (input.Substring(index, 2 )== aa
{
count ++;
}
}

就是这样 - 一个解决简单问题的简单方法。你注意到问题优化了吗?我们知道我们的测试字符串的长度是2,所以匹配可以开始的最后一个位置是最后一个字母的第二个;因此我们从长度上取下1。如果我们试图匹配的文本是三个字符,我们将取2个长度,依此类推。


 string input =caaabaaaa; 
string find =aa;
int count = 0; (b i b = b; b< input.Length; i ++)
$
if(i + find.Length< = input.Length)// validate避免索引错误
{
var str = input.Substring(i,find.Length);
if(str == find)
{
count ++;
}
}
}
Console.WriteLine(count); // 2


我认为答案应该是1,这是一个很好的例子: [ dotnetperls ]

Find the number of occurances of "aa" in "caaab".

The answer should be 2.

What I have tried:

string str = d;
                            for (int number = 0; number < d.Length - genes[i].Length; number++)
                            {
                                var compstr = d.Substring(number, genes[i].Length).ToString();
                                str = d.Substring(1);
                                if (compstr == genes[i])
                                {
                                    count++;
                                }
                            }

解决方案

This is a simple problem to work with but I get surprised at the simple optimisation that people miss in problems like this. Let's take a look at the code first:

for (int index = 0; index < input.Length - 1; index++)
{
  if (input.Substring(index, 2) == "aa")
  {
    count++;
  }
}

And that's it - a simple solution to a simple problem. Did you notice the problem optimisation though? We know that the length of our test string is 2, so the last place that the match can start is the second off last letter; hence the reason we take 1 off the Length. If the text we were trying to match against was three characters, we would take 2 off the length, and so on.


string  input = "caaabaaaa";
string find = "aa";
int count = 0;

for (int i = 0; i < input.Length; i++)
{
    if (  i + find.Length <=input.Length) // validate to avoid index error
    {
        var str = input.Substring(i, find.Length);
        if (str == find)
        {
            count++;
        }
    }
}
Console.WriteLine(count); //2


I think the answer should be 1, here is a nice example: [dotnetperls]


这篇关于找出“aa”的出现次数。在“caaab”中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆