计算以字符“ A”开始并以字符“ X”结束的子字符串 [英] Counting substring that begin with character 'A' and ends with character 'X'

查看:121
本文介绍了计算以字符“ A”开始并以字符“ X”结束的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PYTHON QN:
仅使用一个循环,如何设计一种算法,计算以字符 A 开头并以字符 X ?例如,给定输入字符串 CAXAAYXZA ,有四个子字符串以 A 开头,以 X ,即: AX AXAAYX AAYX AYX

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.

例如:

>>>count_substring('CAXAAYXZA')
4


推荐答案

由于您未指定语言,因此我正在使用c ++ ish

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;
}

和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

这篇关于计算以字符“ A”开始并以字符“ X”结束的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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