17413_단어 뒤집기 2
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
string ns;
stack<char>st;
bool tag = false;
getline(cin, s);
// 개행문자 마다 스트링 객체에 저장하는 입력 방식
for (int i = 0; i < s.size(); i++) {
if (s[i] == '<') {
tag = true;
while (!st.empty()) {
ns += st.top();
st.pop();
} // 스택이 남아 있을 경우 빼냄
ns += s[i]; // '<' 추가
} // tag 시작 부분
else if (s[i] == '>') {
tag = false; // 괄호 종료를 알려줌
ns += s[i]; // '>' 추가
} // tag 끝 부분
else if (tag) {
ns += s[i];
} // 괄호 내부일 경우
else {
if (s[i] == ' ') {
while (!st.empty()) {
ns += st.top();
st.pop();
} // 스택이 남아있을 경우 빼냄
ns += s[i];
} // 공백일 경우
else {
st.push(s[i]);
} // 공백이나 태그외의 문자일 경우
}
}
while (!st.empty()) {
ns += st.top();
st.pop();
} // 스택에 남아 있는 부분이 있으면 꺼냄
cout << ns;
return 0;
}
<aside> 💡 참고할 점
</aside>
10799_쇠막대기
시간 제한 1초, 메모리 제한 : 256MB
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string bk;
stack<char> st;
int count = 0;// 잘린 쇠막대기 개수
cin >> bk;
for (int i = 0; i < bk.size(); i++) {
if (bk[i] == '(') {
st.push(bk[i]);
}
else{ // ')'
st.pop(); // 레이저인 경우
if (bk[i - 1] == '(') {
count += st.size();
} // 쇠막대기가 레이저로 인해 잘렸을 경우
// 스택의 크기 = 레이저가 자르는 쇠막대기의 개수
else {
count += 1; // '))'
}
// 마지막 레이저가 자른 막대기의 마지막 부분 의미
}
}
cout << count;
return 0;
}
<aside> 💡 참고할 점
</aside>
17298_오큰수
#include <bits/stdc++.h>
using namespace std;
int n;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
vector<int> arr(n); // 배열 크기 n인 배열 생성(수열 넣는)
vector<int> ans(n); // 오큰 수 배열
stack<int> st;
for(int i = 0; i < n; i++){
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
if (st.empty()) {
st.push(0);
}
while (!st.empty() && arr[st.top()] < arr[i]) {
ans[st.top()] = arr[i];
st.pop();
} // 스택이 비어 있지 않거나 다음 인덱스의 값이 더 클 경우
st.push(i);
// 다음 인덱스 값 작을 경우 인덱스번호 스택에 넣어 주기만 함
}
while (!st.empty()) {
ans[st.top()] = -1;
st.pop();
} // 반복문 나왔을 때(오큰 수 없을 경우)
for (int i = 0; i < n; i++) {
cout << ans[i] << ' ';
} // 오큰 수 배열 출력
return 0;
}
<aside> 💡 참고할 점
</aside>
17299_오등큰수