Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Leetcode 2375. Construct Smallest Number From DI String

Woodyiiiiiii opened this issue · comments

My strategy: 深度遍历DFS

time complexity: > O(n)

class Solution {
    public String smallestNumber(String pattern) {
        PriorityQueue<String> queue = new PriorityQueue<>();
        Set<Integer> set = new HashSet<>();
        StringBuilder sb = new StringBuilder();

        dfs(sb, pattern, 0, set, queue);

        return queue.isEmpty() ? "" : queue.peek();
    }
    
    private void dfs(StringBuilder sb, String pattern, int idx, Set<Integer> set, PriorityQueue<String> queue) {
        if (sb.length() == pattern.length() + 1) {
            queue.offer(sb.toString());
            return;
        }

        for (int num = 1; num <= 9; num++) {
            if (set.contains(num)) {
                continue;
            }
            if (idx > 0) {
                int n = Integer.parseInt(sb.charAt(idx - 1) + "");
                if (pattern.charAt(idx - 1) == 'I') {
                    if (num < n) {
                        continue;
                    }
                } else if (pattern.charAt(idx - 1) == 'D') {
                    if (num > n) {
                        continue;
                    }
                }
            }
            sb.append(num);
            set.add(num);
            dfs(sb, pattern, idx + 1, set, queue);
            sb.deleteCharAt(sb.length() - 1);
            set.remove(num);
        }
    }
}

use stack to reverse:

class Solution {
    public String smallestNumber(String pattern) {
        StringBuilder res = new StringBuilder(), stack = new StringBuilder();
        for (int i = 0; i <= pattern.length(); i++) {
            stack.append((char)('1' + i));
            if (i == pattern.length() || pattern.charAt(i) == 'I') {
                res.append(stack.reverse());
                stack = new StringBuilder();
            }
        }
        return res.toString();
    }
}

time complexity: O(n)

relative problem: