1. 程式人生 > >Valid Number 判斷一個string是不是有效地數字表達式 @LeetCode

Valid Number 判斷一個string是不是有效地數字表達式 @LeetCode

題目:

判斷一個string是不是有效地數字表達式

思路:

繁瑣,先移除前導零和字尾零,然後記錄點和e的位置。

再分情況討論。

這道題看了看網上的解法,很多都做得很麻煩。其實我覺得,這道題就是考察正則表示式。

package Level2;

/**
 * Valid Number
 * 
 *  Validate if a given string is numeric.

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.


 *
 */
public class S65 {

	public static void main(String[] args) {

	}

	public boolean isNumber(String s) {
        if(s.trim().isEmpty()){
        	return false;
        }
        String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";
        if(s.trim().matches(regex)){
        	return true;
        }else{
        	return false;
        }
    }
}

推薦一些較好的教程:

Second try:

面試時如果只用正則表示式估計不行,所以寫了下面的方法,其實還算比較直觀,把幾種情況分出來也就好寫了!

public static boolean isNumber(String s) {
		int i = 0;
		while(s.charAt(i) == ' '){	// 移除前導whitespace
			i++;
			if(i >= s.length()){
				return false;
			}
		}
		if(s.charAt(i)=='+' || s.charAt(i)=='-'){	// 忽略符號位
			i++;
		}
		int j = s.length()-1;
		while(s.charAt(j) == ' '){	// 移除字尾whitespace
			j--;
		}
		if(i <= j){
			s = s.substring(i, j+1);
		}else{
			return false;
		}
		
		int dot = -1;	// 記錄點的位置
		int ee = -1;	// 記錄e的位置
		for(i=0; i<s.length(); i++){
			if(dot==-1 && s.charAt(i)=='.'){
				dot = i;
			}else if(ee==-1 && s.charAt(i)=='e'){
				ee = i;
				if(i+1<s.length() && (s.charAt(i+1)=='-' || s.charAt(i+1)=='+')){
					i++;
				}
			}else{
				if(Character.isDigit(s.charAt(i))){
					continue;
				}else{
					return false;
				}
			}
		}
		
		//xxx.xxexx
		String startStr, midStr, lastStr;
		if(dot==-1 && ee==-1){	//xxx  
			startStr = s;	// xxx
			if(startStr.length()<1){
				return false;
			}
		}else if(dot!=-1 && ee==-1){	//xxx.yyy  
			startStr = s.substring(0, dot);	// xxx
			midStr = s.substring(dot+1);		// yyy
			if(startStr.length()<1 && midStr.length()<1){
				return false;
			}
		}else if(dot==-1 && ee!=-1){	// xxxeyyy
			startStr = s.substring(0, ee);	// xxx
			if(startStr.length()<1){
				return false;
			}
			if(ee+1<s.length() && (s.charAt(ee+1)=='-' || s.charAt(ee+1)=='+')){	// xxxe-zz
				lastStr = s.substring(ee+2);	// zz
			}else{
				lastStr = s.substring(ee+1);
			}
			if(lastStr.length() < 1){
				return false;
			}
		}else{		//xxx.yyezz
			if(dot>ee){		// 位置不對
				return false;
			}
			startStr = s.substring(0, dot);	// xxx
			midStr = s.substring(dot+1, ee);	// yy
			if(startStr.length()<1 && midStr.length()<1){
				return false;
			}
			if(ee+1<s.length() && (s.charAt(ee+1)=='-' || s.charAt(ee+1)=='+')){
				lastStr = s.substring(ee+2);	// zz
			}else{
				lastStr = s.substring(ee+1);
			}
			if(lastStr.length() < 1){
				return false;
			}
		}
		return true;
	}