ภาพรวม
ได้รับตัวแปรสตริง str ที่เก็บโค้ดต้นฉบับ คำนวณขนาดสตริง ส่งให้ฟังก์ชัน งานคือจัดรูปแบบโค้ดต้นฉบับให้อ่านง่าย (Pretty print) โดยจัดการอินเดนต์และขึ้นบรรทัดใหม่ตามสัญลักษณ์พิเศษ
ตัวอย่าง
อินพุต − string str =
"#include <bits/stdc++.h> using namespace std; int main()"
"{ int sum, first, second; sum = first + second; printf(\"%d\", c);"
" return 0;}"
เอาต์พุต −
#include <bits/stdc++.h> using namespace std; int main(){
int sum, first, second;
sum = first + second;
printf("%d", c);
return 0; }
อินพุต − string str =
"#include<bits/stdc++.h> using namespace std; int main()"
"{ printf(\"%d\", c);"
" return 0;}"
เอาต์พุต −
#include<bits/stdc++.h> using namespace std; int main(){
printf("%d", c);
return 0; }
แนวทางการแก้ปัญหา
- รับสตริง
strคำนวณความยาว เก็บในlength - เรียก
Rearrangement(str, length) - ภายในฟังก์ชัน
Rearrangement:- ประกาศ
str_1สำหรับผลลัพธ์ ตัวแปรParenthesis,Braces,count,i,jเริ่มต้น 0 - Do-while วนรอบแต่ละตัวอักษร:
- หากเจอ
#<>;}{():- หาก
{เพิ่มBraces - หาก
}ลดBraces - หาก
<และParenthesis==0เพิ่มcount - หาก
>และParenthesis==0ลดcount - หาก
(ตั้งcount=0เพิ่มParenthesis - หาก
)ลดParenthesis - หาก
Parenthesis>0เพิ่มตัวอักษรในstr_1 - มิฉะนั้น หาก
)เพิ่มตัวอักษรในstr_1 - มิฉะนั้น หาก
{หรือ}เพิ่ม newline, ตัวอักษร, newline - มิฉะนั้น หาก
count>0เพิ่มตัวอักษรในstr_1 - มิฉะนั้น หาก
#เพิ่ม newline, ตัวอักษร - มิฉะนั้น เพิ่มตัวอักษร, newline
- หาก
- มิฉะนั้น เพิ่มตัวอักษรใน
str_1เพิ่มi
- หากเจอ
- เพิ่ม null terminator
\0ลงstr_1 - วนลูปพิมพ์
str_1[i]ทุกตัว
ตัวอย่างโค้ด C++
#include <bits/stdc++.h> using namespace std; void Rearrangement(string str, int length){ string str_1; int Parenthesis = 0; int Braces = 0; int count = 0; int i = 0; int j = 0; do{ if(str[i] == '#' || str[i] == '<' || str[i] == '>' || str[i] == ';' || str[i] == '}' || str[i] == '{' || str[i] == '(' || str[i] == ')'){ if(str[i] == '{'){ Braces++; } if(str[i] == '}'){ Braces--; } if(str[i] == '<' && Parenthesis == 0){ count++; } if(str[i] == '>' && Parenthesis == 0){ count--; } if(str[i] == '('){ count = 0; Parenthesis++; } if(str[i] == ')'){ Parenthesis--; } if(Parenthesis > 0){ str_1 = str_1 + str[i]; } else { if(str[i] == ')'){ str_1 = str_1 + str[i]; } else if(str[i] == '{' || str[i] == '}'){ str_1 = str_1 + '\n'; str_1 = str_1 + str[i]; str_1 = str_1 + '\n'; } else if(count > 0){ str_1 = str_1 + str[i]; } else if(str[i] == '#'){ str_1 = str_1 + '\n'; str_1 = str_1 + str[i]; } else { str_1 = str_1 + str[i]; str_1 = str_1 + '\n'; } } } else { str_1 = str_1 + str[i]; } i++; } while (i < length); str_1 = str_1 + '\0'; for(i = 0; i < str_1.length(); i++){ cout << str_1[i]; } } int main(){ string str = "#include <bits/stdc++.h>using namespace std;int main()" "{ int sum, first, second; sum = first + second; printf(\"%d\", c);" " return 0;}"; int length = str.length(); Rearrangement(str, length); return 0; }ผลลัพธ์
#include <bits/stdc++.h> using namespace std; int main() { int sum, first, second; sum = first + second; printf("%d", c); return 0; } - ประกาศ