solve by DFA(Deterministic finite automaton )


  • 0
    A
    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    #include <algorithm>
    #include <stack>
    #include <ctime>
    #include <cstring>
    #include <cctype>
    
    
    using std::stack;
    using std::endl;
    using std::cout;
    using std::cin;
    using std::vector;
    using std::string;
    
    class Solution {
    public:
    	int myAtoi(string str) 
    	{
    		int ind = 0;
    		while (true)
    		{
    			bool flag = false;
    			switch (str[ind])
    			{
    			case '\n': case '\t': case '\v': case '\r': case'\f': case ' ': ++ind; break;
    			default: flag = true; break;
    			}
    			if (flag) break;
    		}
    
    		enum State { A, B, C };
    		State s = A;
    		bool sign = false;
    		long long res = 0;
    		int cnt = 0;
    		string temp;
    		bool flag = false;
    		while (true)
    		{
    			switch (s)
    			{
    			case A: 
    				if (str[ind] == '-') { flag = true; ++ind; s = B; }
    				else if (str[ind] == '+') { flag = false; ++ind; s = B; }
    				else if (std::isdigit(str[ind])) { ++cnt; temp += str[ind++]; s = C; }
    				else return 0;
    				break;
    			case B:
    				if (std::isdigit(str[ind])) { ++cnt; temp += str[ind++]; s = C; }
    				else return 0;
    				break;
    			case C:
    				if (std::isdigit(str[ind]) && cnt <= 10)
    				{
    					++cnt;
    					temp += str[ind++];
    				}
    				else
    				{
    
    
    					for (int i = 0; i < cnt; ++i)
    						res = res * 10 + (temp[i]-'0');
    					res = flag ? -res : res;
    					if (res < INT_MIN)
    						return INT_MIN;
    					else if (res > INT_MAX)
    						return INT_MAX;
    					else
    						return res;
    				}
    				break;
    			}
    		}
    	}
    
    it's a way. but it's really long and inappropriate.
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.