原文:

给定一个字符串,使得每个字符以重复的方式出现。您的任务是通过在字符串后插入每个唯一字符的频率并消除所有重复字符来打印字符串。 例:

input : geeeeekkkss
output : g1e3e2k3s2
input : ccccoddeee
output : c4o1d2e3

解决上述问题的一种方法是开始一个循环,直到字符串结束,并且对于每次迭代,递增一个计数,直到第 i 位置的字符与下面的字符匹配。 下面是对上面给定问题的实现。

c

// cpp program to print run
// length encoding of a string
#include 
using namespace std;
void printrle(string s)
{
    for (int i = 0; s[i] != '\0'; i  ) {
        // counting occurrences of s[i]
        int count = 1;
        while (s[i] == s[i   1]) {
            i  ;
            count  ;
        }
        cout << s[i] << count << " ";
    }
    cout << endl;
}
// driver code
int main()
{
    printrle("geeeeekkkss");
    printrle("ccccoddeee");
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to print run
// length encoding of a string
class gfg {
    static void printrle(string s)
    {
        for (int i = 0; i < s.length(); i  ) {
            // counting occurrences of s[i]
            int count = 1;
            while (i   1 < s.length()
                   && s.charat(i)
                          == s.charat(i   1)) {
                i  ;
                count  ;
            }
            system.out.print(s.charat(i)
                               ""   count   " ");
        }
        system.out.println();
    }
    // driver code
    public static void main(string args[])
    {
        printrle("geeeeekkkss");
        printrle("ccccoddeee");
    }
}
// this code is contributed
// by arnab kundu

python 3

# python 3 program to print run
# length encoding of a string
def printrle(s) :
    i = 0
    while( i < len(s) - 1) :
        # counting occurrences of s[i]
        count = 1
        while s[i] == s[i   1] :
            i  = 1
            count  = 1
            if i   1 == len(s):
                break
        print(str(s[i])   str(count),  
                          end = " ")
        i  = 1
    print()
# driver code
if __name__ == "__main__" :
    # function calling
    printrle("geeeeekkkss")
    printrle("cccc0ddeee")
# this code is contributed by ankitrai1

c

// c# program to print run
// length encoding of a string
using system;
class gfg {
    static void printrle(string s)
    {
        for (int i = 0;
             i < s.length - 1; i  ) {
            // counting occurrences of s[i]
            int count = 1;
            while (s[i] == s[i   1]) {
                i  ;
                count  ;
                if (i   1 == s.length)
                    break;
            }
            console.write(s[i]   ""   count   " ");
        }
        console.writeline();
    }
    // driver code
    public static void main(string[] args)
    {
        printrle("geeeeekkkss");
        printrle("ccccoddeee");
    }
}
// this code contributed by rajput-ji

java 描述语言


output: 

g1 e3 e2 k3 s2 
c4 o1 d2 e3