Alternating Characters

Sort by

recency

|

1981 Discussions

|

  • + 0 comments
    def alternatingCharacters(s):
        # Write your code here
        i=0
        count = 0
        s = list(s)
        while i < len(s) - 1:
            if s[i] == s[i+1]: 
                count+=1
                s.remove(s[i+1])
                continue
            i+=1
        return count
    
  • + 0 comments

    Java:

    public static int alternatingCharacters(String s) {
        int deletions = 0;
    
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                deletions++;
            }
        }
    
        return deletions;
    }
    
  • + 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