按字符串中字符的出现频率降序排列

给出一个字符串,我想根据其字符减少的频率对其进行排序。 如果计数相同,则字符应按字母顺序排序。

brew cask reinstall intellij-idea-ce

到目前为止,这是我的代码:

function substring(string,start,end) {
    var result = '',length = Math.min(string.length,end),i = start;
  
    while (i < length) result += string[i++];
    return result;
}

console.log(substring('This is a string',4));
console.log(substring('This is a string',40,4));

在Objects.keys(map).sort()语句的开头出现“意外令牌”错误。我一生无法弄清楚哪里出了问题。

对于此问题的任何帮助或见解,将不胜感激。

shadowryo 回答:按字符串中字符的出现频率降序排列

一种实现方法是利用语言功能,例如:

let str = "Lorem ipsum dolor sit amet,Consectetur adipiscing elit,"

let newStr = 
  str.split('').sort().join('').match(/(\w)\1*/g).sort(
    (x,y) => y.length - x.length
  ).join('')

console.log(newStr)

将字符串splits放入数组,按值sorts将其joins放入正则表达式/(\w)\1*/g的字符串matched中返回具有所有字符组的数组。反过来,该数组按其元素的长度排序,然后再次连接为字符串。

,

用C ++解决

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>

struct Node
{
    char ch;
    int total;
    Node(char ch,int total){
        this->ch = ch;
        this->total = total;
    }
};


bool mySort(Node a,Node b){
    if(a.total == b.total){
        return a.ch < b.ch;
    }
    return (a.total > b.total);
}

std::string solve(std::string &s){
    std::vector<Node> nodes;
    std::map<char,int> m;
    for (int i = 0; i < s.size(); ++i)
    {
        std::map<char,int>::iterator it = m.find(s[i]);
        if(it != m.end()){
            // Exists
            Node *node = &nodes[it->second];
            node->total++;
        }else{
            Node node(s[i],1);
            nodes.push_back(node);
            m[s[i]] = nodes.size() - 1;
        }
    }

    std::sort(nodes.begin(),nodes.end(),mySort);

    std::string str = "";
    for (int i = 0; i < nodes.size(); ++i)
    {
        for (int j = 0; j < nodes[i].total; ++j)
        {
            str += nodes[i].ch;
        }

    }

    return str;
}

int main()
{
    std::string s = "Programming";
    std::string result = solve(s);
    std::cout << "Result is: " << result;

    return 0;
}

对于JavaScript

var s = "Programming";
var map = {};
var nodes = [];

for(var i = 0; i < s.length; ++i){
	var it = map[s[i]];
	if(typeof it !== "undefined"){
  	//exist
    nodes[it].total ++;
  }else{
  	map[s[i]] = nodes.length;
    nodes.push({total: 1,ch: s[i]});
  }
}

nodes = nodes.sort(function(a,b){
	if(a.total < b.total){
	  return 1;
  }
  if(a.total == b.total){
  	if(a.ch < b.ch){
    	return -1;
    }else{
    	return 1;
    }
  }
  return 0;
});

var result = "";
for(var i =0; i < nodes.length; ++i){
	var node = nodes[i];
	for(var j = 0; j < node.total; ++j){
  	result += node.ch;
  }
}

console.log(result);

本文链接:https://www.f2er.com/3128846.html

大家都在问