1. 程式人生 > >leetcode - Valid Number

leetcode - Valid Number

data true cbe scan -a false style return can

題目:

Valid Number

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true



class Solution {
public:
	bool isNumber(string s) {
		if (s.empty())
			return false;
		//刪除開頭和結尾的空格
		//刪除開頭空格
		if (s[0] == ‘ ‘)
		{
			int i = 1;
			while (i<s.size() && s[i] == ‘ ‘)
				++i;
			s.erase(s.begin(), s.begin() + i);
		}
		//刪完開頭空格後若為空,則返回假
		if (s.empty())
			return false;
		int size = s.size();
		//刪除結尾空格
		if (s[size - 1] == ‘ ‘)
		{
			int i = size - 2;
			while (i >= 0 && s[i] == ‘ ‘)
				--i;
			if (i<0)
				return false;
			s.erase(s.begin() + i + 1, s.end());
		}
		//刪除結尾空格後,若為空或以‘e‘開頭,返回假
		if (s.empty() || s[0] == ‘e‘ || s[0] == ‘E‘)
			return false;
		//若仍然有空格,返回假
		if (s.find(" ") != string::npos)
			return false;

		size = s.size();
		int index = 0;
		if (s[index] == ‘+‘ || s[index] == ‘-‘)
			++index;
		//僅僅有加減號,返回假
		if (index == size)
			return false;
		//若第一個小數點前有數字,docbeforenum為真
		bool docbeforenum = false;
		if (s[index] >= ‘0‘ && s[index] <= ‘9‘)
			docbeforenum = true;
		scanNumber(s, index);
		//一個整數,返回真
		if (index == size)
			return true;

		bool res = true;
		//小數
		if (s[index] == ‘.‘)
		{
			++index;
			//‘.‘是字符串最後一位時。‘.‘前有數字則返回真,否則返回假
			if (index == size)
			{
				return docbeforenum;
			}
			//‘.‘後緊跟著非數字時
			if (s[index]<‘0‘ || s[index]>‘9‘)
			{
				if ((s[index] == ‘e‘ || s[index] == ‘E‘) && docbeforenum)
				{
					// “數字.e” 的形式。繼續推斷
				}
				else
					return false;
			}

			scanNumber(s, index);
			//小數的形式,返回真
			if (index == size)
				return true;
			if (s[index] == ‘e‘ || s[index] == ‘E‘)
				res = isExp(s, index);
		}
		else if (s[index] == ‘e‘ || s[index] == ‘E‘)
		{
			// ‘e‘前沒有數字,返回假
			if (docbeforenum == false)
				return false;
			res = isExp(s, index);
		}
		else
			res = false;

		return res && s[index] == ‘\0‘;
	}

	//遇到數字則往後走
	void scanNumber(const string &s, int &index)
	{
		int size = s.size();
		while (index<size && s[index] >= ‘0‘ && s[index] <= ‘9‘)
			++index;
	}

	//推斷以‘e‘開頭的字符串能否代表指數
	bool isExp(const string &s, int &index)
	{
		++index;
		int size = s.size();
		//僅僅有一個‘e‘,返回假
		if (index == size)
			return false;
		if (s[index] == ‘+‘ || s[index] == ‘-‘)
			++index;
		//‘e‘後沒有數字,返回假
		if (index == size || s[index]<‘0‘ || s[index]>‘9‘)
			return false;
		scanNumber(s, index);
		return true;
	}
};


leetcode - Valid Number