[One question per day] Two sorting methods

Source title
cattle off network
links: Two Methods for Priorities

Title description
Koala has n character strings, any two strings are different in length. Koala recently learned that there are two ways to sort strings:
1. Sort the strings in lexicographic order. For example:
"car" <"carriage" <"cats" <"doggies <"koala"
2. Sort according to the length of the string. For example:
"car" <"cats" <"koala" <"doggies" <"carriage"
Koala wants to know whether the sequence of these strings meets these two sorting methods. Koala is busy eating leaves, so you need to help verify it.

Enter a description:

Enter the number of strings in the first line n (n ≤ 100) and the
next n lines, each line has a character string, the length of the character string is less than 100, and all consist of lowercase letters

Output description:

If these strings are arranged in lexicographic order instead of length, output "lexicographically".
If they are arranged according to length instead of lexicographically, output "lengths".
If both methods are in line, output "both", otherwise output "none"

enter:

3
a
aa
bbb

Output:

both

The idea of ​​solving the problem The idea
is very simple. Put the accepted strings into the vector container, use the operator>= operator overload of string to compare strings according to ascii, and use the size of string to compare the length of the strings.

Code display

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    
    
	int n;
	cin >> n;
	vector<string> v;
	v.resize(n);
	for(auto& str : v)
		cin >> str;
	bool lenSym = true, lexSym = true;
	// 这里要注意从i=1开始遍历,前后比较,比较长度
	for(size_t i = 1;i < v.size();++i)
	{
    
    
		if(v[i - 1].size() >= v[i].size())
		{
    
    
			lenSym = false;
			break;
		}
	}
	//比较ASCII码
	for(size_t i = 1;i < v.size();++i)
	{
    
    
		if(v[i - 1] >= v[i])
		{
    
    
			lexSym = false;
			break;
		}
	}
	if(lenSym && lexSym)
		cout << "both" << endl;
	else if(!lenSym && lexSym)
		cout << "lexicographically" << endl;
	else if(lenSym && !lexSym)
		cout << "lengths" << endl;
	else if(!lenSym && !lexSym)
		cout << "none" << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/zhao_leilei/article/details/110655472