在C语言中,字符串中任意两个相同字符之间的最大字符数
我们得到一个字母字符串。数组中至少会有两个相同字符的出现。这里的任务是找到任意两个相同字符之间的最大字符数。如果没有任何字符的重复,则返回-1。
输入 - 字符串 str = "abcdba"
输出 - 字符串中任意两个相同字符之间的最大字符数 - 4
解释 - 重复的字符只有'a'和'b',它们的索引为-
1. 2‘a’ first index 0 last 5 , characters in between 5-0-1=4 2. ‘b’ first index 1 last 4 , characters in between 4-1-1=2 Maximum character in between repeating alphabets : 4登录后复制
输出 - 字符串中任意两个相同字符之间的最大字符数 - 5
解释 - 重复的字符是 ‘A’,‘b’,‘c’,它们的索引如下:
1. ‘A’ first index 0 last 3 , characters in between 3-0-1=2 2. ‘b’ first index 1 last 7 , characters in between 7-1-1=5 3. ‘c’ first index 2 last 6 , characters in between 6-2-1=3 Maximum character in between repeating alphabets : 5登录后复制
下面程序中使用的方法如下
我们使用一个字符数组来存储字符串 Str[]
函数 maxChars( char str[],int n) 用于计算任意两个重复字母之间的最大字符数。
我们将变量 maxC 初始化为-1。
在 for 循环中从字符串的开头遍历数组。
在嵌套的 for 循环中遍历剩余的字符,并搜索是否有重复字符(如果 str[i] == str[j])。
如果为真,则通过减去索引计算字符之间的差异(temp = j - i - 1)。
如果这个值是迄今为止找到的最大值,则将其存储在 maxC 中。
在遍历整个字符串后,返回 maxC。
示例
演示
#include #include #include int maxChars(char str[],int n){ int size = n; int maxC = -1; for (int i = 0; i temp?maxC:temp; } return maxC; } // Driver code int main(){ char Str[] = "AbcAaBcbC"; printf("Maximum number of characters between any two same character in a string :%d", maxChars(Str,9) ); return 0; }登录后复制