※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 25204번 문제인 문자열 정렬이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/25204 

 

25204번: 문자열 정렬

예제 1: "Aa-" 문자열이 두 번 주어졌으므로 두 번 출력해야 한다. "Aa-" 와 "a-A"를 비교하면 첫 글자가 다르므로 규칙 2-2에 따라 "Aa-"가 사전순으로 앞선다. 예제 2: "Saint-Louis" 와 "Saint-Paul" 의 경우 'L

www.acmicpc.net

문제에서 주어진 두 문자열 사이 우선순위를 비교하는 함수를 만들어 정렬을 하는 문제이다.

 

주어진 내용과 같이 비교함수를 작성한 뒤 std::sort의 세번째 인자로 집어넣어 문제를 해결해주자. 아래의 구현과 같이 tolower과 같은 함수를 이용하면 편리하게 구현할 수 있다.

 

아래는 제출한 소스코드이다.

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

int T;
bool comp(string& s1, string& s2) {
	int idx1 = 0, idx2 = 0;
	while (idx1 < s1.length() && idx2 < s2.length()) {
		if (s1[idx1] == s2[idx2]) idx1++, idx2++;
		else {
			if (s1[idx1] == '-') return 0;
			if (s2[idx2] == '-') return 1;
			if (tolower(s1[idx1]) != tolower(s2[idx2])) return tolower(s1[idx1]) < tolower(s2[idx2]);
			return s1[idx1] < s2[idx2];
		}
	}
	return s1 < s2;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> T;
	while (T--) {
		int N; cin >> N;
		vector<string> vec;
		while (N--) {
			string s; cin >> s;
			vec.emplace_back(s);
		}
		sort(vec.begin(), vec.end(), comp);

		for (auto& s : vec) cout << s << '\n';
	}
}
728x90

+ Recent posts