[leetcode]Valid Number

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   strong   for   ar   

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.

演算法思路:

排除法:遇到所有非法情況則返回false,掃描完之後返回true

非法情況:

符號:+、-最多隻能出現兩次,而且第二次必須出現在e/E後面。而且第一個+/-號之前必須沒有數字,第二個比如緊接在e後面,而且後面必須有數字;

e:最多隻能出現一次。而且前後必須有數字;

. : 最多隻能出現一次,而且不能出現在e後面,.如果在字串最後一位時,前面必須要有數字;

【提交出錯後補充】第一次提交的時候,“e”報錯,邊界情況沒有考慮真是不應該

總之這種題,不難,但是繁瑣:

給出我出錯的case,希望大家借鑒:(好多啊,囧)

005047e+6 true

3. true

.1 true

-. false

6+1 false

. 1 false

0e false

代碼如下:

 1 public class Solution { 2     public boolean isNumber(String s) { 3         if(s == null || s.trim().length() == 0) return false; 4         s = s.trim(); 5         char[] charArray = {‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,‘.‘,‘e‘,‘E‘,‘+‘,‘-‘}; 6         Set<Character> set = new HashSet<Character>(); 7         for(char c : charArray){ 8             set.add(c); 9         }10         boolean hasE = false, hasPoint = false, hasNum = false;11         int operaterCount = 0;12         for(int i = 0; i < s.length(); i++){13             if(!set.contains(s.charAt(i))) return false;14             if(s.charAt(i) <= ‘9‘ && s.charAt(i) >= ‘0‘) hasNum = true;15             if(s.charAt(i) == ‘E‘ || s.charAt(i) == ‘e‘){16                 if(i == 0 || i == s.length() - 1) return false;17                 if(!hasE && hasNum) hasE = true;18                 else return false;19             }20             if(s.charAt(i) == ‘.‘){21                 if(i == 0 && 1 == s.length()) return false;22                 if(i == s.length() - 1 && !hasNum) return false;23                 if(!hasPoint && !hasE) hasPoint = true;24                 else return false;25             }26             if(s.charAt(i) == ‘-‘ || s.charAt(i) == ‘+‘){27                 if(i == s.length() - 1 || (i != 0 && s.charAt(i - 1) != ‘e‘ && s.charAt(i - 1) != ‘E‘)) return false;28                 if(operaterCount == 2) return false;29                 if(operaterCount == 1 && !hasE && !hasNum) return false;30                 operaterCount++;31             }32         }33         return true;34     }35 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.