string에도 back/ front가 가능하다.
좋다.
#include <string>
#include <vector>
#include <iostream>
#include <unordered_set>
using namespace std;
vector<int> solution(int n, vector<string> words) {
unordered_set <string> setDuplicate;
string prevWord(1, words[0].front()); //첫 단어의 첫 글자로 초기화
int count = 0;
bool isBreak = false;
for (const string& word : words)
{
//중복 또는 끝말잇기 실패
if (setDuplicate.end() != setDuplicate.find(word) || prevWord.back() != word.front())
{
isBreak = true;
break;
}
setDuplicate.insert(word);
prevWord = word;
++count;
}
vector<int> answer;
if (isBreak)
{
answer.push_back(count % n + 1); //row
answer.push_back(count / n + 1); //colrm
}
else
{
return { 0, 0 };
}
return answer;
}
개선할 점
반복문 i로 count 대체 가능.
answer 생각안하면 더 빠른 반환이 가능하지만, 주어진 걸 무시할 순 없잖아.
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
vector<int> solution(int n, vector<string> words) {
unordered_set<string> usedWords;
string previousWord = "";
for (int i = 0; i < words.size(); ++i) {
string currentWord = words[i];
// 첫 번째 단어 또는 끝말잇기 규칙 위반 검사
if (i > 0 && (previousWord.back() != currentWord.front() || usedWords.find(currentWord) != usedWords.end())) {
return {i % n + 1, i / n + 1}; // 탈락자 번호 및 차례 반환
}
usedWords.insert(currentWord);
previousWord = currentWord;
}
return {0, 0}; // 모든 단어를 정상적으로 통과한 경우
}
set.insert 첫 값은 true, 중복은 false를 반환한다고 한다.
'학습(0) > C++ 문제풀이' 카테고리의 다른 글
할인 행사 (0) | 2025.03.08 |
---|---|
전화번호 목록 / 해시 (0) | 2025.03.08 |
완주하지 못한 선수 (0) | 2025.03.07 |
다리를 지나는 트럭 (0) | 2025.03.07 |
컨트롤 Z/프로그래머스 no matching 에러. (0) | 2025.03.05 |