给定一个字符串,任务是找到字符与同相邻的字符数。
注意:第一个和最后一个字符将始终被计数,因为它们只有一个相邻的字符。
例子:
Input: str = “egeeksk”
Output: 4
Characters with same adjacent characters are e, g, s, k
Input: str = “eeeeeeee”
Output: 8
Characters with same adjacent characters are e, e, e, e, e, e, e, e
方法:
- 如果字符串的长度小于3,则返回字符串的长度。
- 用2初始化计数,因为第一个和最后一个总是被计数。
- 开始遍历字符串。
- 检查当前字符的前面和后面的字符是相同的。
- 增量计数(如果是)。
- 返回计数。
下面是上述方法的实现:
C++
// C++ implementation of bove approach
#include
using namespace std;
// Function to count the characters
// with same adjacent chracters
int countChar(string str)
{
int n = str.length();
// if length is less than 3
// then return length as there
// will be only two characters
if (n <= 2)
return n;
int count = 2;
// Traverse the string
for (int i = 1; i < n - 1; i++)
// Increment the count if the previous
// and next character is same
if (str[i - 1] == str[i + 1])
count++;
// Return count
return count;
}
// Driver code
int main()
{
string str = "egeeksk";
cout << countChar(str);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to count the characters
// with same adjacent chracters
static int countChar(String str)
{
int n = str.length();
// if length is less than 3
// then return length as there
// will be only two characters
if (n <= 2)
return n;
int count = 2;
// Traverse the string
for (int i = 1; i < n - 1; i++)
// Increment the count if the previous
// and next character is same
if (str.charAt(i - 1) == str.charAt(i + 1))
count++;
// Return count
return count;
}
// Driver code
public static void main(String []args)
{
String str = "egeeksk";
System.out.println(countChar(str));
}
}
// This code is contributed
// by ihritik
Python3
# Python 3 implementation of bove approach
# Function to count the characters
# with same adjacent chracters
def countChar(str):
n = len(str)
# if length is less than 3
# then return length as there
# will be only two characters
if (n <= 2):
return n
count = 2
# Traverse the string
for i in range(1, n - 1):
# Increment the count if the previous
# and next character is same
if (str[i - 1] == str[i + 1]):
count += 1
# Return count
return count
# Driver code
if __name__ == '__main__':
str = "egeeksk"
print(countChar(str))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of above approach
using System;
class GFG
{
// Function to count the characters
// with same adjacent chracters
static int countChar(String str)
{
int n = str.Length;
// if length is less than 3
// then return length as there
// will be only two characters
if (n <= 2)
return n;
int count = 2;
// Traverse the string
for (int i = 1; i < n - 1; i++)
// Increment the count if the previous
// and next character is same
if (str[i - 1] == str[i + 1])
count++;
// Return count
return count;
}
// Driver code
public static void Main()
{
String str = "egeeksk";
Console.WriteLine(countChar(str));
}
}
// This code is contributed
// by Subhadeep
PHP
输出:
4