Alternating Characters

Sort by

recency

|

1955 Discussions

|

  • + 0 comments
        count = 0
        i = 0
        for i in range(i, len(s)-1):
           if s[i] == s[i+1]:
              count = count + 1         
        return count
            
    
  • + 0 comments

    Here are my c++ approaches of solving this, video explanation here : https://youtu.be/KoDlxS38_ig

    Solution 1 : Using loop

    int alternatingCharacters(string s) {
        int result = 0;
        for(int i = 1; i < s.size(); i++) if(s[i] == s[i-1]) result++;
        return result;
    }
    

    Solution 2 : Using regex

    int alternatingCharacters(string s) {
        regex re("A{2,}|B{2,}");
        return s.size() - regex_replace(s, re, "*").size();
    }
    
  • + 0 comments

    def alternatingCharacters(s): n = len(s) count = 0 for i in range(n-1): if s[i] == s[i+1]: count += 1 return count

  • + 0 comments

    php

    function alternatingCharacters($s) {
        // Write your code here
        $stack = [];
        $deletions = 0;
        for ($i = 0; $i < strlen($s); $i++) {
            if (count($stack) === 0) {
                $stack[] = $s[$i];
            } else {
                $last = $stack[count($stack) - 1];
                if ($last === $s[$i]) {
                    $deletions++;
                } else {
                    $stack[] = $s[$i];
                }
            }
        }
        return $deletions;
    }
    
  • + 0 comments
    public static int alternatingCharacters(String s) {
        // Write your code here
        int count = 0 ;
        for (int i = 1 ; i < s.length(); i++){
            if(s.charAt(i) == s.charAt(i-1)){
                count +=1;
            }
        }
        return count;
    
        }