题解
【入门】合法的变量名
2 条题解
-
0
1. 解题思路
先将非空名称的合法标志初始化,再检查首位、题目指定的四个禁用词,以及每个字符是否属于英文字母、数字或下划线;违反任何一项就判为非法。
2. 坑点和注意事项
合法标志必须初始化,否则合法输入可能读到未定义的旧值。首位不能为数字,空名称非法;只排除题目指定的int、double、cin、cout,不扩大为所有C++关键字。英文字母按ASCII范围检查,空格和标点不能混入名称。
3. 复杂度
- 时间复杂度:O(L),L为名称长度。
- 空间复杂度:O(L),保存名称字符串。
/* 思路:先排除空串、数字开头和四个禁用词,再检查每个字符是否合法。 关键:字母、数字、下划线可出现在后续位置,首字符不能是数字。 坑点:判定标志必须初始化;本题仅禁用指定四词,不套用完整C++关键字表。 时间复杂度:O(n),n为名称长度。 空间复杂度:O(n);名称长度不超过20,下标用int。 */ #include <bits/stdc++.h> using namespace std; int main() { string s; getline(cin, s); if (!s.empty() && s.back() == '\r') { s.pop_back(); } bool flag = !s.empty(); if (!s.empty() && s[0] >= '0' && s[0] <= '9') { flag = false; } if (s == "int" || s == "double" || s == "cout" || s == "cin") { flag = false; } for (int i = 0; i < (int)s.size(); i++) { char c = s[i]; bool a = c >= 'A' && c <= 'Z', b = c >= 'a' && c <= 'z'; // 显式比较ASCII范围,不让空格和标点混入名称。 if (!a && !b && !(c >= '0' && c <= '9') && c != '_') { flag = false; } } if (flag) { cout << "yes" << endl; } else { cout << "no" << endl; } return 0; } -
0
#include<bits/stdc++.h> using namespace std; int main(){ string s; bool f; getline(cin,s); for(int i=0;i<s.size();i++){ if((isdigit(s[i])||isalpha(s[i])||s[i]=='_')==false){ f=false; break; } } if(isdigit(s[0])){ f=false; } if(s=="int"||s=="double"||s=="cin"||s=="cout"){ f=false; } if(f==false){ cout<<"no"; } else{ cout<<"yes"; } return 0; }
- 1