How to print given string with it's count of repeated characters. [Like below]?


  • 0
    P

    My solution doesn't work for all use case.

    ===
    aaaaaa -> 6a
    aaabbbcc -> 3a3b2c
    aabbbaaaa -> 2a3b4b [This one doesn't work]

    """
    charHash = {}

    def numChar(string):
    for c in string:
    if c in charHash:
    charHash[c] += 1
    else:
    charHash[c] = 1

    if name=="main":
    numChar("xxyyyxxxx")

    print charHash
    

    """

    What logic should i apply?


  • 0

    c#

    
                string s = "aabbaa";
                Dictionary<char, int> d = new Dictionary<char, int>();
                string output = "";
                char lastChar = ' ';
    
                foreach (char c in s)
                {
                    
                    if(d.ContainsKey(c) && lastChar == c)
                    {
                        d[c] += 1;
                    }
                    else if (d.ContainsKey(c) && lastChar != c)
                    {
                        // add to output what we already have
                        foreach(KeyValuePair<char, int> kvp in d)
                        {
                            output += kvp.Key.ToString() + kvp.Value.ToString();
                        }
    
                        d = new Dictionary<char, int>();
                        d.Add(c, 1);
                    }
                    else if (!d.ContainsKey(c))
                    {
                        
                        d.Add(c, 1);                    
                    }
    
    
                    lastChar = c;
    
                    
                }
    
                // output final 
                foreach (KeyValuePair<char, int> kvp in d)
                {
                    output += kvp.Key.ToString() + kvp.Value.ToString();
                }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.