题解 | #把字符串转换成整数#
表示数值的字符串
http://www.nowcoder.com/practice/e69148f8528c4039ad89bb2546fd4ff8
基本思路:用一个栈来存+-eE.这些符号
遍历所有字符串
对于+-:当在第一位时候入栈;不在第一位且前面没有任何符号,或者前一个符号不是e的时候,直接false,否则入栈
对于e:不能出现在第一或者最后一位,或是紧跟在+-.之后;其他情况下入栈。
对于.:不能出现在首尾,不能出现在e或者另一个.之后;其他情况下入栈。
对于数字;0不能在首位,当栈头是+-时候,pop一次;
其他字符直接false;
最后检查末尾是不是+-.e
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @return bool布尔型
*/
bool isNumeric(string str) {
// write code here
stack<char> ope;
for(int i =0;i<str.size();i++){
if(str[i]=='+'||str[i]=='-'){
if(i==0) ope.push(str[i]);
else if(ope.empty()) return false;
else{
if(ope.top()=='+' || ope.top() == '-' || ope.top()=='.') return false;
else ope.push(str[i]);
}
}
else if(str[i]=='e'||str[i]=='E'){
if(i==0 || i==str.size()-1) return false;
if(str[i-1]=='.') return false;
if(ope.empty()){
ope.push(str[i]);
}
else{
if(ope.top()=='+' || ope.top() == '-') return false;
else ope.push(str[i]);
}
}
else if(str[i]=='.'){
if(i==0 || i==str.size()-1) return false;
if(ope.empty()){
ope.push(str[i]);
}
else{
// if(ope.top()=='+' || ope.top() == '-') return false;
if(ope.top()=='e'||ope.top()=='E') return false;
if(ope.top()=='.') return false;
}
}
else if(str[i]=='0' && i==0) return false;
else if(str[i]>='0' && str[i]<='9'){
if(!ope.empty()){
if(ope.top()=='+' || ope.top() == '-') ope.pop();
}
}
else return false;
}
if(!ope.empty()){
if(ope.top()=='+' || ope.top() == '-') return false;
if(ope.top()=='.' && (str[str.size()-1]<'0' || str[str.size()-1]>'9')) return false;
}
return true;
}
};
滴滴公司福利 1784人发布