[Codewars] Weight for weight

Weight for weight

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <bits/stdc++.h>
using namespace std;
class WeightSort
{
public:
static std::string orderWeight(const std::string &strng) {
unordered_map<string, long long> weight;
vector<string> S;
string now = "";
long long cost = 0;
for(auto ch : strng) {
if(ch == ' ') {
if(now.length()) {
weight[now] = cost;
S.push_back(now);
now = "", cost = 0;
}
} else now.push_back(ch), cost += ch - '0';
}
if(now.length()) {
weight[now] = cost;
S.push_back(now);
now = "", cost = 0;
}

sort(begin(S), end(S), [&](auto& a, auto& b) {
if(weight[a] != weight[b]) return weight[a] < weight[b];
return a < b;
});
string res = "";
for(auto s : S) res += s + " ";
while(res.length() and res.back() == ' ') res.pop_back();
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/29/PS/Codewars/weight-for-weight/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.