Alternating Characters

Sort by

recency

|

1977 Discussions

|

  • + 0 comments

    Here is a python O(n) time and O(1) space solution:

    def alternatingCharacters(s):
        ch = s[0]
        remove = 0
        
        for i in range(1, len(s)):
            if s[i] == ch:
                remove += 1
            
            if s[i] != ch:
                ch = s[i]
        
        return remove 
    
  • + 0 comments
    public static int alternatingCharacters(String str) {
        int firstptr=0;
        int secondptr = firstptr+1;
        int totaldeletions = 0;
        while(secondptr < str.length()) {
            if(str.charAt(firstptr) == str.charAt(secondptr)) {
                totaldeletions++;
                secondptr++;
            } else {
                firstptr = secondptr;
                secondptr++;
            }
        }
        return totaldeletions;        
    }
    
  • + 0 comments
    def alternatingCharacters(s):
        # Write your code here
        c = 0
        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                c += 1
        return c
    
  • + 0 comments

    Here is problem solution in python java c++ c and javascript - https://programmingoneonone.com/hackerrank-alternating-characters-solution.html

  • + 0 comments

    Simple loop based C++ Solution:

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