题目描述
Give some strings that consist of “0” and “1”, you sort them by the number of “1” in the string, and if they have the same number , then sort by the position of the “1” appears, the more lately ‘1’ appears, the string is the more “bigger” of . such as the string “00110” should stand behind the string “11000”, “111001” should stand behind the string “111010”. The output should remain they original order to those strings that has no ‘1’ at all.
输入
The first line N is the number of strings(N<=100). The next N lines is the strings to be sort. ( the length of each string is less than 100 )
输出
The sorted strings
样例输入
8 000 000111000 1100001 101100001 0000000 000110001 101110 00000
样例输出
000 0000000 00000 1100001 000111000 000110001 101110 101100001
我的解法:
#include <iostream>
using namespace std;
#define MAX 100
int n = 0, k = 0;
/*judge if the string contains '1'*/
bool hasOne(string str)
{
int len = str.size();
for (int i = 0; i < len; i++)
{
if (str[i] == '1')
{
return true;
}
}
return false;
}
/*the count of '1'*/
int countOfOne(string str)
{
int cou = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == '1')
{
cou++;
}
}
return cou;
}
int cmpPos(string src, string dest)
{
int len = src.size() <= dest.size() ? src.size() : dest.size();
int i = 0;
for (i = 0; i < len; i++)
{
if (src[i] == '1')
{
if (dest[i] != '1')
{ // src < dest
return -1;
}
else
{
continue;
}
}
else
{
if (dest[i] == '1')
{ // src > dest
return 1;
}else {
continue;
}
}
}
// src == dest
return 0;
}
/*compare two strings*/
int strCmp(string src, string dest){
if (countOfOne(src) < countOfOne(dest)){ // src < dest
return -1;
}else if (countOfOne(src) > countOfOne(dest)){ // src > dest
return 1;
}else{ // the count of character '1' in src and dest is equal
return cmpPos(src, dest);
}
}
/*bubble sort*/
void strSort(string strs[])
{
for (int i = 0; i < k - 1; i++)
{
for (int j = 0; j < k -1; j++)
{
if (strCmp(strs[j], strs[j + 1]) == 1)
{ // strs[j] > strs[j+1]
string temp = strs[j];
strs[j] = strs[j + 1];
strs[j + 1] = temp;
}
}
}
}
int main()
{
string src[MAX], dest[MAX], temp[MAX];
cin >> n;
int j = 0;
for (int i = 0; i < n; i++)
{
cin >> temp[i];
if (!hasOne(temp[i]))
{
dest[j++] = temp[i];
}
else
{
src[k++] = temp[i];
}
}
strSort(src);
for (int i = 0; i < n; i++)
{
dest[j++] = src[i];
}
for (int i = 0; i < n; i++)
{
cout << dest[i] << endl;
}
return 0;
}