题目
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. ATM机允许4位或6位PIN码,PIN码只能包含4位或6位。 如果向函数传递了有效的PIN字符串,则返回true,否则返回false。
例子
“1234” —> true “12345” —> false “a234” —> false
分析
解法一
- 判断字符串长度 4位或 6 位
- 字符串遍历
-
解法二
写正则表达式 判断是否是4或6位的纯数字
-
我的解法
```java import java.util.regex.Pattern; public class Solution {
public static boolean validatePin(String pin) { return Pattern.compile(“[\d]{4}|[\d]{6}”).matcher(pin).matches(); }
}
<a name="SIKo6"></a>### 参考解法```javaimport java.util.regex.*;public class Solution {public static boolean validatePin(String pin) {return pin.matches("\\d{4}|\\d{6}");}}
public class Solution {public static boolean validatePin(String pin) {if (pin == null || (pin.length() != 4 && pin.length() != 6)) {return false;}for (int i = 0; i < pin.length(); i++) {if (!Character.isDigit(pin.charAt(i))) {return false;}}return true;}}
提升
- 利用正则表达式可以极大简化操作
- 如果表达式需要匹配多次,要先进行预编译(设置成静态常量),加快匹配速度。
