Valid Password

本文介绍了一种算法,用于判断在1-9数字键盘中有一个按键损坏的情况下,输入的密码是否有效。通过两个指针分别遍历预期密码和实际输入密码,并记录损坏按键,最后验证是否匹配。

Problem

In 1-9 keypad one key is not working. If someone enters a password then not working key will not be entered. You have given expected password and entered password. Check that entered password is valid or not. Ex: entered 164, expected 18684 (you need to take care as when u enter18684 and 164 only both will be taken as 164 input)

Solution


有几种情况需要考虑下, 

1. 没有按到过坏的键

2. 1864, 1684.  坏的是8, 坏的键又出现一次

2. expect有可能是186848888,要继续检查直到长度相等

 1 public static boolean validPassword(String expect, String actual) {
 2     char faultKey = '\0'; //initial fault key
 3     int i=0, j=0;    //two pointer for each string
 4     for(; i<actual.length() && j<expect.length(); j++) {
 5         if(actual.charAt(i) != expect.charAt(j)) {
 6             if(faultKey == '\0')    faultKey = expect.charAt(j);    //record fault key
 7             else if(faultKey != expect.charAt(j))    return false;    //found second fault key
 8             i--;
 9         }
10         i++;
11     }
12     
13     for(int k=0; k<expect.length() ;k++) {
14         if(faultKey == expect.charAt(k)) return false;            
15     }
16     //fault key may require press many times after that
17     while(j<expect.length() && expect.charAt(j)==faultKey)    j++;
18     
19     return (i==actual.length() && j==expect.length() && faultKey == '\0') ? true : false;
20 }

 

转载于:https://www.cnblogs.com/superbo/p/4111923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值