替换字符串中的通配符?
/*
* 给定字符串(合法字符只包括0,1,?),替换字符串中的通配符?为0或者1,生成所有可能的字符串。
* Input str = "1??0?101"
* Output:
* 10000101
* 10001101
* 10100101
* 10101101
* 11000101
* 11001101
* 11100101
* 11101101
*/
其实这道题用到了深度优先搜索,深度优先搜索呢是这样的,建立在图上的数据结构,是图的搜索算法之一,在深度优先搜索算法中,每条边最多会被访问两次,一次是遍历,一次是回退。回溯的过程,然后所以时间复杂度是 O(E)。 它的空间复杂度因为递归函数调用不会栈的深度不会超过顶点的个数,所以深度优先搜索的空间复杂度为 O(V)。
public class Test22 {
        public static void main(String[] args){
            String s = "1??0?101";
            System.out.println(generateString(s));
        }
        private static List<String> result;
        private static char[] sc;
        public static List<String> generateString(String s) {
            result = new ArrayList<>();
            sc = s.toCharArray();
            helper(0);
            return result;
        }
        private static void helper(int index) {
            if (index == sc.length) {
                result.add(new String(sc));
                return;
            }
            if (sc[index] == '?') {
                sc[index] = '0';
                helper(index + 1);
                sc[index] = '1';
                helper(index + 1);
                sc[index] = '?';
            } else {
                helper(index + 1);
            }
        }
    }
  

京公网安备 11010502036488号