Alternating Characters

Sort by

recency

|

1979 Discussions

|

  • + 0 comments

    C Solution :

    int alternatingCharacters(char* s) {
        int i=0,j,count=0;
        while(s[i]!='\0'){
        char ch = s[i];
        j=i+1;
        while(s[j]==s[i] && s[j]!='\0'){
            j++;
            i++;
            count++;
        }
        if(s[j]=='\0')
            break;
        i++;
      }
      return count;
    }
    
  • + 0 comments
    def alternatingCharacters(s:str):
        
        count = 0
        for i in range(len(s)-1):
            if s[i] == s[i+1]:
                count +=1
        return count
    
  • + 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