Alternating Characters

Sort by

recency

|

1971 Discussions

|

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

    Here is a Python3 implemention. It is intentionally verbose to ensure explainability:

    from collections import Counter
    def isValid(orig_string):
        # Create a dict with the count of all characters
        string_collect = Counter(list(orig_string))
        str_c = sorted(string_collect.values())
        
        # If the first and last are the same then all characters are equal
        if str_c[0] == str_c[-1]:
            return "YES"
            
        # If the largest count is only one larger than every other value
        elif str_c[-1] == str_c[-2] + 1 and str_c[0] == str_c[-2]:
            return "YES"
            
        # If the smallest count is only one smaller than every other value OR the smallest count is 1 (therefore can be removed completely)
        elif (str_c[1] == str_c[0] + 1 or str_c[0] == 1)and str_c[1] == str_c[-1]:
            return "YES"
            
        else:
            return "NO"
    
  • + 0 comments

    Java Solution for this with single forloop with O(n) Complexity public static int alternatingCharacters(String s) { // Write your code here StringBuffer buffer = new StringBuffer(); int count = 0; for(int i = 1; i < s.length(); i++){ if(s.charAt(i) == s.charAt(i - 1)){ count++;
    }
    } return count; }``

  • + 0 comments

    def alternatingCharacters(s):

        # Write your code here
    deletions=0
    for i in range(1,len(s)):
        if s[i-1]==s[i]:
            deletions+=1
    return deletions