Open In App

Count characters with same neighbors

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, the task is to find the number of characters with the same adjacent characters. 

Note: First and last character will always be counted as they will have only one adjacent character.

Examples:

Input: str = “egeeksk” 
Output:
Characters with same adjacent characters are e, g, s, k

Input: str = “eeeeeeee” 
Output:
Characters with same adjacent characters are e, e, e, e, e, e, e, e

Approach: 

  1. If the length of the string is less than 3 then return the length of the string.
  2. Initialize the count with 2 as first and last will always be counted.
  3. Start traversing the string.
    • Check if the previous and next characters of the current character are the same.
    • Increment count, if yes.
  4. Return count.

Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the characters
// with same adjacent characters
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 characters
     
        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 above approach
 
# Function to count the characters
# with same adjacent characters
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 characters
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




<?php
// PHP implementation of above approach
 
// Function to count the characters
// with same adjacent characters
function countChar($str)
{
    $n = strlen($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 = 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
$str = "egeeksk";
echo countChar($str);
 
// This code is contributed by Sach
?>


Javascript




<script>
 
// Javascript implementation of above approach
 
// Function to count the characters
// with same adjacent characters
function countChar(str)
{
    var n = str.length;
 
    // if length is less than 3
    // then return length as there
    // will be only two characters
    if (n <= 2)
        return n;
    var count = 2;
 
    // Traverse the string
    for (var 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
var str = "egeeksk";
document.write( countChar(str));
 
</script>


Output

4

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Example in c:

Approach:

Initialize a counter variable to zero, which will keep track of the number of characters with the same neighbors.

Initialize three variables, prev, curr, and next, to the first three characters of the string.

Traverse the string from the fourth character to the last character:

a. Update the prev, curr, and next variables to the previous, current, and next characters, respectively.

b. If the curr character is the same as both the prev and next characters, increment the counter variable.

Return the counter variable.

C++




#include <iostream>
#include <cstring>
 
using namespace std;
 
int count_same_neighbors(char *str) {
    int len = strlen(str);
    int count = 0;
    char prev = str[0];
    char curr = str[1];
    char next = str[2];
     
    // Traverse the string and count characters with the same neighbors
    for (int i = 3; i < len; i++) {
        prev = curr;
        curr = next;
        next = str[i];
         
        if (prev == curr && curr == next) {
            count++;
        }
    }
     
    // Return the count of characters with the same neighbors
    return count;
}
 
int main() {
    char str[] = "aabbccddddee";
    int count = count_same_neighbors(str);
    cout << "Number of characters with the same neighbors: " << count << endl;
     
    return 0;
}


C




#include <stdio.h>
#include <string.h>
 
int count_same_neighbors(char *str) {
    int len = strlen(str);
    int count = 0;
    char prev = str[0];
    char curr = str[1];
    char next = str[2];
     
    // Traverse the string and count characters with the same neighbors
    for (int i = 3; i < len; i++) {
        prev = curr;
        curr = next;
        next = str[i];
         
        if (prev == curr && curr == next) {
            count++;
        }
    }
     
    // Return the count of characters with the same neighbors
    return count;
}
 
int main() {
    char str[] = "aabbccddddee";
     
    int count = count_same_neighbors(str);
     
    printf("Number of characters with the same neighbors: %d\n", count);
     
    return 0;
}


Java




public class Main {
    public static int countSameNeighbors(String str)
    {
        int len = str.length();
        int count = 0;
        char prev = str.charAt(0);
        char curr = str.charAt(1);
        char next = str.charAt(2);
 
        // Traverse the string and count characters with the
        // same neighbors
        for (int i = 3; i < len; i++) {
            prev = curr;
            curr = next;
            next = str.charAt(i);
 
            if (prev == curr && curr == next) {
                count++;
            }
        }
 
        // Return the count of characters with the same
        // neighbors
        return count;
    }
 
    public static void main(String[] args)
    {
        String str = "aabbccddddee";
        int count = countSameNeighbors(str);
        System.out.println(
            "Number of characters with the same neighbors: "
            + count);
    }
}


Python3




def count_same_neighbors(str):
    length = len(str)
    count = 0
    prev = str[0]
    curr = str[1]
    next = str[2]
 
    # Traverse the string and count characters with the same neighbors
    for i in range(3, length):
        prev = curr
        curr = next
        next = str[i]
 
        if prev == curr and curr == next:
            count += 1
 
    # Return the count of characters with the same neighbors
    return count
 
str = "aabbccddddee"
count = count_same_neighbors(str)
print("Number of characters with the same neighbors: ", end = "")
print(count)


C#




using System;
 
class Program {
  static int CountSameNeighbors(string str)
  {
    int len = str.Length;
    int count = 0;
    char prev = str[0];
    char curr = str[1];
    char next = str[2];
 
    // Traverse the string and count characters with the
    // same neighbors
    for (int i = 3; i < len; i++) {
      prev = curr;
      curr = next;
      next = str[i];
 
      if (prev == curr && curr == next) {
        count++;
      }
    }
 
    // Return the count of characters with the same
    // neighbors
    return count;
  }
 
  static void Main(string[] args)
  {
    string str = "aabbccddddee";
    int count = CountSameNeighbors(str);
    Console.WriteLine(
      "Number of characters with the same neighbors: "
      + count);
  }
}


Javascript




function count_same_neighbors(str) {
    let len = str.length;
    let count = 0;
    let prev = str[0];
    let curr = str[1];
    let next = str[2];
 
    // Traverse the string and count characters with the same neighbors
    for (let i = 3; i < len; i++) {
        prev = curr;
        curr = next;
        next = str[i];
 
        if (prev == curr && curr == next) {
            count++;
        }
    }
 
    // Return the count of characters with the same neighbors
    return count;
}
 
let str = "aabbccddddee";
let count = count_same_neighbors(str);
console.log("Number of characters with the same neighbors: " + count);


Output

Number of characters with the same neighbors: 2

time complexity of O(n) 

 space complexity of O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads