原文:

给定字符串字符串只包含小写字符。问题是按照字符出现的顺序和下面示例中解释的给定格式打印字符及其频率。

示例:

input : str = "geeksforgeeks"
output : g2 e4 k2 s2 f1 o1 r1
input : str = "elephant"
output : e2 l1 p1 h1 a1 n1 t1

来源:

方法:创建一个计数数组来存储给定字符串中每个字符的频率字符串。再次遍历字符串字符串,检查该字符的频率是否为 0。如果不是 0,则打印字符及其频率,并在哈希表中将其频率更新为 0。这样做是为了不再打印相同的字符。

c

// c   implementation to print the character and
// its frequency in order of its occurrence
#include 
using namespace std;
#define size 26
// function to print the character and its frequency
// in order of its occurrence
void printcharwithfreq(string str)
{
    // size of the string 'str'
    int n = str.size();
    // 'freq[]' implemented as hash table
    int freq[size];
    // initialize all elements of freq[] to 0
    memset(freq, 0, sizeof(freq));
    // accumulate frequency of each character in 'str'
    for (int i = 0; i < n; i  )
        freq[str[i] - 'a']  ;
    // traverse 'str' from left to right
    for (int i = 0; i < n; i  ) {
        // if frequency of character str[i] is not
        // equal to 0
        if (freq[str[i] - 'a'] != 0) {
            // print the character along with its
            // frequency
            cout << str[i] << freq[str[i] - 'a'] << " ";
            // update frequency of str[i] to 0 so
            // that the same character is not printed
            // again
            freq[str[i] - 'a'] = 0;
        }
    }
}
// driver program to test above
int main()
{
    string str = "geeksforgeeks";
    printcharwithfreq(str);
    return 0;
}

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

// java implementation to print the character and
// its frequency in order of its occurrence
public class char_frequency {
    static final int size = 26;
    // function to print the character and its
    // frequency in order of its occurrence
    static void printcharwithfreq(string str)
    {
         // size of the string 'str'
        int n = str.length();
        // 'freq[]' implemented as hash table
        int[] freq = new int[size];
        // accumulate frequency of each character
        // in 'str'
        for (int i = 0; i < n; i  )
            freq[str.charat(i) - 'a']  ;
        // traverse 'str' from left to right
        for (int i = 0; i < n; i  ) {
            // if frequency of character str.charat(i)
            // is not equal to 0
            if (freq[str.charat(i) - 'a'] != 0) {
                // print the character along with its
                // frequency
                system.out.print(str.charat(i));
                system.out.print(freq[str.charat(i) - 'a']   " ");
                // update frequency of str.charat(i) to
                // 0 so that the same character is not
                // printed again
                freq[str.charat(i) - 'a'] = 0;
            }
        }
    }
    // driver program to test above
    public static void main(string args[])
    {
        string str = "geeksforgeeks";
        printcharwithfreq(str);
    }
}
// this code is contributed by sumit ghosh

python 3

# python3 implementation to pr the character and
# its frequency in order of its occurrence
# import library
import numpy as np
# function to print the character and its
# frequency in order of its occurrence
def prcharwithfreq(str) :
    # size of the 'str'
    n = len(str)
    # initialize all elements of freq[] to 0
    freq = np.zeros(26, dtype = np.int)
    # accumulate frequency of each
    # character in 'str'
    for i in range(0, n) :
        freq[ord(str[i]) - ord('a')]  = 1
    # traverse 'str' from left to right
    for i in range(0, n) :
        # if frequency of character str[i] 
        # is not equal to 0
        if (freq[ord(str[i])- ord('a')] != 0) :
            # print the character along
            # with its frequency
            print (str[i], freq[ord(str[i]) - ord('a')],
                                                end = " ")
            # update frequency of str[i] to 0 so that
            # the same character is not printed again
            freq[ord(str[i]) - ord('a')] = 0
# driver code
if __name__ == "__main__" :
    str = "geeksforgeeks";
    prcharwithfreq(str);
# this code is contributed by 'saloni1297'

c

// c# implementation to print the
// character and its frequency in
// order of its occurrence
using system;
class gfg {
    static int size = 26;
    // function to print the character and its
    // frequency in order of its occurrence
    static void printcharwithfreq(string str)
    {
        // size of the string 'str'
        int n = str.length;
        // 'freq[]' implemented as hash table
        int[] freq = new int[size];
        // accumulate frequency of each character
        // in 'str'
        for (int i = 0; i < n; i  )
            freq[str[i] - 'a']  ;
        // traverse 'str' from left to right
        for (int i = 0; i < n; i  ) {
            // if frequency of character str.charat(i)
            // is not equal to 0
            if (freq[str[i] - 'a'] != 0) {
                // print the character along with its
                // frequency
                console.write(str[i]);
                console.write(freq[str[i] - 'a']   " ");
                // update frequency of str.charat(i) to
                // 0 so that the same character is not
                // printed again
                freq[str[i] - 'a'] = 0;
            }
        }
    }
    // driver program to test above
    public static void main()
    {
        string str = "geeksforgeeks";
        printcharwithfreq(str);
    }
}
// this code is contributed by sam007

服务器端编程语言(professional hypertext preprocessor 的缩写)


java 描述语言


output

g2 e4 k2 s2 f1 o1 r1 

时间复杂度: o(n),其中 n 为字符串中的字符数。 辅助空格: o(1),因为只有小写字母。

替代pg电子试玩链接的解决方案(使用哈希) 我们也可以使用哈希来解决问题。

c

// c   implementation to
//print the characters and
// frequencies in order
// of its occurrence
#include 
using namespace std;
void prcharwithfreq(string s)
{
  // store all characters and
  // their frequencies in dictionary
  unordered_map d;
  for(char i : s)
  {
    d[i]  ;
  }
  // print characters and their
  // frequencies in same order
  // of their appearance
  for(char i : s)
  {
    // print only if this
    // character is not printed
    // before
    if(d[i] != 0)
    {
      cout << i << d[i] << " ";
      d[i] = 0;
    }
  }
}
// driver code
int main()
{
  string s="geeksforgeeks";
  prcharwithfreq(s);
}
// this code is contributed by rutvik_56

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

// java implementation to
// print the characters and
// frequencies in order
// of its occurrence
import java.util.*;
class gfg{
    public static void prcharwithfreq(string s)
    {
        // store all characters and
        // their frequencies in dictionary
        map d = new hashmap();
        for(int i = 0; i < s.length(); i  )
        {
            if(d.containskey(s.charat(i)))
            {
                d.put(s.charat(i), d.get(s.charat(i))   1);
            }
            else
            {
                d.put(s.charat(i), 1);
            }
        }
        // print characters and their
        // frequencies in same order
        // of their appearance
        for(int i = 0; i < s.length(); i  )
        {
            // print only if this
            // character is not printed
            // before
            if(d.get(s.charat(i)) != 0)
            {
                system.out.print(s.charat(i));
                system.out.print(d.get(s.charat(i))   " ");
                d.put(s.charat(i), 0);
            }           
        }
    }
    // driver code
     public static void main(string []args)
     {
       string s = "geeksforgeeks";
       prcharwithfreq(s);
     }
}
// this code is contributed by avanitrachhadiya2155

python 3

# python3 implementation to print the characters and
# frequencies in order of its occurrence
def prcharwithfreq(str):
    # store all characters and their frequencies
    # in dictionary
    d = {}
    for i in str:
        if i in d:
            d[i]  = 1
        else:
            d[i] = 1
    # print characters and their frequencies in
    # same order of their appearance
    for i in str:
        # print only if this character is not printed
        # before. 
        if d[i] != 0:
            print("{}{}".format(i,d[i]), end =" ")
            d[i] = 0
# driver code
if __name__ == "__main__" :
    str = "geeksforgeeks";
    prcharwithfreq(str);
# this code is contributed by 'ankur tripathi'

c

// c# implementation to
// print the characters and
// frequencies in order
// of its occurrence
using system;
using system.collections;
using system.collections.generic;
class gfg
{
public static void prcharwithfreq(string s)
{
  // store all characters and
  // their frequencies in dictionary
  dictionary d = new dictionary();
  foreach(char i in s)
  {
      if(d.containskey(i))
      {
        d[i]  ;
      }
      else
      {
        d[i]=1; 
      }
  }
  // print characters and their
  // frequencies in same order
  // of their appearance
  foreach(char i in s)
  {
    // print only if this
    // character is not printed
    // before
    if(d[i] != 0)
    {
        console.write(i d[i].tostring()   " ");
        d[i] = 0;
    }
  }
}
// driver code
public static void main(string []args)
{
  string s="geeksforgeeks";
  prcharwithfreq(s);
}
}
// this code is contributed by pratham76

java 描述语言


output

g2 e4 k2 s2 f1 o1 r1 

方法 3:使用内置的 python 函数:

我们可以使用 python 方法快速解决这个问题。方法很简单。

1)首先使用 counter 方法创建一个字典,将字符串作为键,将它们的频率作为值。

2)在本词典中遍历打印关键字及其值

python 3

# python3 implementation to print the characters and
# frequencies in order of its occurrence
from collections import counter
def prcharwithfreq(string):
    # store all characters and their
    # frequencies suing counter function
    d = counter(string)
    # print characters and their frequencies in
    # same order of their appearance
    for i in d:
        print(i str(d[i]), end=" ")
string = "geeksforgeeks"
prcharwithfreq(string)
# this code is contributed by vikkycirus

output

g2 e4 k2 s2 f1 o1 r1 

本文由阿育什·乔哈里供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。