Alternating Characters

Sort by

recency

|

1959 Discussions

|

  • + 0 comments

    Java:

    public static int alternatingCharacters(String s) {
      if (s.length() <= 1) {
        return 0;
      }
    
      int deletions = 0;
    
      for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(i - 1)) {
          deletions++;
        }
      }
      return deletions;
    }
    
  • + 0 comments
    def alternatingCharacters(s):
        b_s=s.split('A')
        a_s=s.split('B')
        print(a_s,b_s)
        ans=0
        for i in a_s:
            if 'A' in i :
                ans+=(len(i)-1)
        for j in b_s:
            if 'B' in j :
                ans+=(len(j)-1)
        return ans
    

    optimized version below

    def alternatingCharacters(s):
        deletions = 0 
        for i in range(1, len(s)):  
            if s[i] == s[i - 1]:  
                deletions += 1 
        return deletions   
    
  • + 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):

    lp=count=0
    rp=1
    while lp<len(s) and rp<len(s):
        if s[lp]==s[rp]:
            count+=1
        lp+=1
        rp+=1
    return count
    
  • + 0 comments
    def alternatingCharacters(s):
        s2 = re.sub(r'([AB])\1+', r'\1', s)
        return len(s) - len(s2)