다음 파이썬 코드를 def check(data): s = [] tag = False temp = '' for i in range(len(data)): if…
- User
다음 파이썬 코드를 def check(data): s = [] tag = False temp = '' for i in range(len(data)): if data[i] == '<': tag = True elif data[i] == '>': tag = False if temp and temp[-1] == '/': temp = '' continue elif s and s[-1] == temp[1:]: s.pop() else: s.append(temp) temp = ''
codeif tag and data[i] == ' ' and data[i + 1] != '/': tag = False if tag and data[i] != '<': temp += data[i] if s: print("illegal") else: print("legal")while True: data = input() if data == '#': break else: check(data)
C++로 작성해보았어.
#include <bits/stdc++.h> using namespace std;
int main() { ios::sync_with_stdio(0); cin.tie(0);
codewhile (true) { stack<string> S; string input; getline(cin, input); if (input == "#") break; bool tag = false; string cur = ""; for (int i = 0; i < input.size(); i++) { if (input[i] == '<') { tag = true; } else if (input[i] == '>') { tag = false; if (input[i - 1] == '/') { cur = ""; continue; } else if (!S.empty() && "/" + S.top() == cur) { S.pop(); } else { S.push(cur); cur = ""; } } if (tag && input[i] == ' ') tag = false; if (tag && input[i] != '<') cur += input[i]; } if (S.empty()) cout << "legal" << '\n'; else cout << "illegal" << '\n'; } return 0;}
일부 수정한 부분이 있는데, 혹시 문제가 되는 부분이 있을까?
- Assistant
C++로 변환된 코드를 살펴보았으멈 몇 가지 문제가 있어 보입니다.
-
태그 이름 처리: Python 코드에서는
'<'또는'>'가 나타날 때마다 일시적으로 tag를 처리하고temp를 클리어합니다. 그러나 C++ 코드에서cur는 태그가 끝나면('>') 항상 비우지 않습니다. 찾아보니, 태그를 닫았을 경우와 새로운 태그가 시작될 때cur를 초기화하고 있지 않습니다. -
태그 사이 공백 처리의 누락: Python 코드에서는 태그 내에 공백이 나타나면 로 설정하여 태그 처리를 즉시 중단하고 있습니다. C++ 코드에서는 이 부분이 제대로 반영되지 않았는지 확인이 필요합니다.
-