【LeetCode】47. Longest Common Prefix

题目描述(Hard)

Validate if a given string is numeric.

题目链接

https://leetcode.com/problems/valid-number/description/

Example 1:

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

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

算法分析

【剑指】20.表示数值的字符串 + 首尾去空格

提交代码:

class Solution {
public:
	bool isNumber(string s) {
		if (s.empty()) return false;
		const char *str = s.c_str();

		while (*str == ' ') ++str;
		bool result = scanSignedInt(&str);

		if (*str == '.')
		{
			++str;
			// 小数点前后都可以没有数字
			result = scanUnsignedInt(&str) || result;
		}

		if (*str == 'e' || *str == 'E')
		{
			++str;
			result = scanSignedInt(&str) && result;
		}
		while (*str == ' ') ++str;
		return result && *str == '\0';
	}


	bool scanUnsignedInt(const char **str)
	{
		const char *before = *str;
		while (isdigit(**str))
			++*str;

		return *str > before;
	}

	bool scanSignedInt(const char **str)
	{
		if (**str == '+' || **str == '-')
			++*str;
		return scanUnsignedInt(str);
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string str, bool expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	bool result = s.isNumber(str);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("0"), true);
	Test("Test2", string(" 0.1 "), true);
	Test("Test3", string("abc"), false);
	Test("Test4", string("1 a"), false);
	Test("Test5", string("2e10"), true);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82460064