LeetCode OJ - Valid Number
發現一個不錯的解法~
See Problem!
If you want to use (copy, paste or quote) my original article,
please contact me through email. (autek.roy@gmail.com)
If there is any mistake or comment, please let me know. :D
如要使用(複製貼上或轉載)作者原創文章, 請來信跟我聯絡。(autek.roy@gmail.com) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )
發現一個不錯的解法~
See Problem!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isNumber(const char *s) { | |
bool point = false, notation = false; | |
int len = strlen(s); | |
int start = 0, end = len; | |
for(int i = start; i < end; i++) | |
if(s[i] == ' ') start++; | |
else break; | |
for(int i = end - 1; i >= 0; i--) | |
if(s[i] == ' ') end--; | |
else break; | |
if(start >= end) return false; | |
if(s[start] == '+' || s[start] == '-') | |
start++; | |
if(s[start] == '.' && ((s[start + 1] < '0') || (s[start + 1] > '9'))) | |
return false;//special case '.' | |
/* this case is right in this problem | |
if(s[start] > '9'|| s[start] < '0') | |
return false;// in case ".0887" | |
*/ | |
if(s[start] == 'e') return false; | |
for(int i = start; i < end; i++){ | |
if(s[i] <= '9' && s[i] >= '0') continue; | |
else if(s[i] == '.'){ | |
start = i + 1;// ex: 904.[4]2 | |
point = true; | |
break; | |
} | |
else if(s[i] == 'e'){ | |
start = i + 1; | |
if(s[start] == '+' || s[start] == '-') | |
start++; | |
notation = true; | |
break; | |
} | |
else return false; | |
} | |
if(point){ | |
if(start >= end) return true; //ex: "90932." | |
//if(s[start] > '9' || s[start] < '0') return false; | |
for(int i = start; i < end; i++){ | |
if(s[i] <= '9' && s[i] >= '0') continue; | |
else if(s[i] == 'e'){ | |
start = i + 1; | |
if(s[start] == '+' || s[start] == '-') | |
start++; | |
notation = true; | |
break; | |
} | |
else return false; | |
} | |
} | |
if(notation){ | |
if(start >= end) return false; | |
else if(s[start] > '9' || s[start] < '0') return false; | |
for(int i = start; i < end; i++) | |
if(s[i] <= '9' && s[i] >= '0') continue; | |
else return false; | |
} | |
return true; | |
} | |
}; |
如要使用(複製貼上或轉載)作者原創文章, 請來信跟我聯絡。(autek.roy@gmail.com) 如果有發現任何的錯誤與建議請留言或跟我連絡。 : )
沒有留言:
張貼留言
請留下您的任何想法或建議!
Please leave any thought or comment!