lintcode(570)寻找丢失的数 II

来源:互联网 发布:cad三维绘图软件 编辑:程序博客网 时间:2024/06/06 00:12

描述:

给一个由 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