LeetCode: Valid Number

leetcode里最恶心的题目。。面试问这种题目可以去撞墙了。。

 自己写了一遍

 1 class Solution {

 2 public:

 3     bool isNumber(const char *s) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         while (isspace(*s)) s++;

 7         if (*s == '+' || *s == '-') s++;

 8         bool space, e, dot, first, second;

 9         space = e = dot = first = second = false;

10         while (*s != '\0') {

11             if (*s == '.') {

12                 if (e || space || dot || second) return false;

13                 dot = true;

14             }

15             else if (*s == 'e') {

16                 if (e || space || !first) return false;

17                 e = true;

18             }

19             else if (isdigit(*s)) {

20                 if (space) return false;

21                 if (!e) first = true;

22                 else second = true;

23             }

24             else if (isspace(*s)) space = true;

25             else if (*s == '+' || *s == '-') {

26                 if (space || *(s-1) != 'e') return false;

27             }

28             else return false;

29             s++;

30         }

31         if (!first) return false;

32         if (e && !second) return false;

33         return true;

34     }

35 };

 C#

 1 public class Solution {

 2     public bool IsNumber(string s) {

 3         int cur = 0;

 4         while (cur < s.Length && s[cur] == ' ') cur++;

 5         if (cur < s.Length && (s[cur] == '+' || s[cur] == '-')) cur++;

 6         bool space, e, dot, first, second;

 7         space = e = dot = first = second = false;

 8         while (cur < s.Length) {

 9             if (s[cur] == '.') {

10                 if (e || space || dot || second) return false;

11                 dot = true;

12             }

13             else if (s[cur] == 'e') {

14                 if (e || space || !first) return false;

15                 e = true;

16             }

17             else if (s[cur] >= '0' && s[cur] <= '9') {

18                 if (space) return false;

19                 if (!e) first = true;

20                 else second = true;

21             }

22             else if (s[cur] == ' ') space = true;

23             else if (s[cur] == '+' || s[cur] == '-') {

24                 if (space || (cur > 0 && s[cur-1] != 'e')) return false;

25             }

26             else return false;

27             cur++;

28         }

29         if (!first) return false;

30         if (e && !second) return false;

31         return true;

32     }

33 }
View Code

 

你可能感兴趣的:(LeetCode)