lintcode(570)寻找丢失的数 II

描述:

给一个由 1 - n 的整数随机组成的一个字符串序列,其中丢失了一个整数,请找到它。

 注意事项

n <= 30

样例:

给出 n = 20, str = 19201234567891011121314151618

丢失的数是 17 ,返回这个数。

思路:

难点在于字符串的分割,采用回溯的方式,如果出现不符合条件的情况,就返回到这一次操作的起始,如果执行到字符串最末,则返回分割结果

public class Solution {
    /**
     * @param n an integer
     * @param str a string with number from 1-n
     *            in random order and miss one number
     * @return an integer
     */
    public int findMissing2(int n, String str) {
        // Write your code here
        if( n < 1 || str == null ){
            return 0;
        }
        int len = str.length();
        int[] index = {0};
        boolean[] exist = new boolean[n + 1];
        search(n , str , index , exist , len);
        for(int i = 1;i<=len;i++){
            if(!exist[i]){
                return i;
            }
        }
        return 0;
    }
    
    public void search(int n , String str , int[] index , boolean[] exist , int len){
        if(index[0] >= len){
            return ;
        }
        if(str.charAt(index[0]) == '0'){
            return ;
        }
        if(!exist[str.charAt(index[0]) - '0']){
            exist[str.charAt(index[0]) - '0'] = true;
            index[0]++;
            search(n , str , index , exist , len);
            if(index[0] >= len){
                return ;
            }
            index[0]--;
            exist[str.charAt(index[0]) - '0'] = false;
        }
        if(index[0] < len - 1){
            int a = str.charAt(index[0]) - '0';
            int b = str.charAt(index[0] + 1) - '0';
            int value = 10*a + b;
            if(value <= n && !exist[value]){
                exist[value] = true;
                index[0] += 2;
                search(n , str , index , exist , len);
                if(index[0] >= len){
                    return ;
                }
                index[0] -= 2;
                exist[value] = false;
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值