Counting substring that begin with character 'A' and ends with character 'X'

扶醉桌前 提交于 2019-12-11 07:17:55

问题


PYTHON QN: Using just one loop, how do I devise an algorithm that counts the number of substrings that begin with character A and ends with character X? For example, given the input string CAXAAYXZA there are four substrings that begin with A and ends with X, namely: AX, AXAAYX, AAYX, and AYX.

For example:

>>>count_substring('CAXAAYXZA')
4

回答1:


Since you didn't specify a language, im doing c++ish

int count_substring(string s)
{
  int inc = 0;
  int substring_count = 0;

  for(int i = 0;i < s.length();i++)
  {
     if(s[i] == 'A') inc++;
     if(s[i] == 'X') substring_count += inc;
  }
  return substring_count;
}

and in Python

def count_substring(s):
   inc = 0
   substring_count = 0
   for c in s:
      if(c == 'A'): inc = inc + 1
      if(c == 'X'): substring_count = substring_count + inc
   return substring_count



回答2:


First count number of "A" in the string Then count "X" in the string

using

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then cnt += 1
  Next
  Return cnt
End Function

then take each "A" as a start position and "X" as an end position and get the substring. Do this for each "X" and then start with second "A" and run that for "X" count times. Repeat this and you will get all the substrings starting with "A" and ending with "X".




回答3:


Just another solution In python:

def count_substring(str):
    length = len(str) + 1
    found = []
    for i in xrange(0, length):
        for j in xrange(i+1, length):
            if str[i] == 'A' and str[j-1] == 'X':
                found.append(str[i:j])
    return found
string = 'CAXAAYXZA'
print count_substring(string)

Output:

['AX', 'AXAAYX', 'AAYX', 'AYX']


来源:https://stackoverflow.com/questions/21349353/counting-substring-that-begin-with-character-a-and-ends-with-character-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!