题解 | #表示数值的字符串#
表示数值的字符串
https://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return bool布尔型 */ bool isNumeric(string str) { int index = 0; int point_num = 0; int num = 0; int e_num = 0; int E_num = 0; while (index < str.size()) { //判断有无符号 //匹配符号 if (str[index] == '+' || str[index] == '-') { if (index + 1 >= str.size() || !((str[index + 1] >= '0' && str[index + 1] <= '9') || str[index + 1] == '.') || (index - 1 >= 0 && str[index - 1] >= '0' && str[index - 1] <= '9')) { return false; } } else if (str[index] == '.') { //匹配小数点 point_num += 1; if (point_num > 1)return false; if ((index + 1 < str.size() && !(str[index + 1] >= '0' && str[index + 1] <= '9' || str[index + 1] == 'e' || str[index + 1] == 'E')) || (index - 1 >= 0 && !((str[index - 1] >= '0' && str[index - 1] <= '9') || str[index - 1] == '+' || str[index - 1] == '-'))) { return false; } } else if (str[index] == 'e' || str[index] == 'E') { //匹配科学计数法 if(str[index] == 'e')e_num += 1; if(str[index] == 'E')E_num += 1; if(e_num + E_num > 1)return false; if (index - 1 < 0 || !((str[index - 1] >= '0' && str[index - 1] <= '9') || str[index - 1] == '.') || index + 1 >= str.size() || !((str[index + 1] >= '0' && str[index + 1] <= '9') || (str[index + 1] == '+' || str[index + 1] == '-'))) { return false; } } if(!(str[index] >= '0' && str[index] <= '9' || str[index] == '.' || str[index] == '+' || str[index] == '-' || str[index] == 'e' || str[index] == 'E' || str[index] == ' ')){ return false; } if(str[index] >= '0' && str[index] <= '9')num += 1; index += 1; } if(e_num > 0 && point_num > 0 && ((strstr(str.c_str(),".") > strstr(str.c_str(),"e"))))return false; if(E_num > 0 && point_num > 0 && ((strstr(str.c_str(),".") > strstr(str.c_str(),"E"))))return false; if(num == 0)return false; return true; } };
题解:根据规则一一匹配,时间复杂度是O(n),空间复杂度是O(1)。这样的解法我称之为shi山代码。