java - 具有原始字符串的所有不同字符的最小长度子字符串的滑动窗口解决方案

标签 java string algorithm

谁能告诉我哪里出错了。下面是我的代码。 这里我使用滑动窗口解决方案,左和右作为指向字符串的指针。 “dist_count”包含字符串中唯一字符的计数。

public class Solution {
    public String findSubstring(String s) {
        if (s == null || s.length() == 0)
            return "";
        int dist_count = 0;
        int[] hash = new int[256]; // character hash
        boolean[] visited = new boolean[256];
        // record each character in s to hash
        for (char c : s.toCharArray()) {
            hash[c]++;
        }
        for (char c : s.toCharArray()) {
            if (visited[c] == false) {
                dist_count++;
                visited[c] = true;
            }
        }
        System.out.println(dist_count);
        int left = 0, right = 0, count = 0;
        int min_window = Integer.MAX_VALUE;
        int startIndex = -1;
        while (right < s.length()) {
            if (hash[s.charAt(right)] >= 1) {
                count++;
            }
            hash[s.charAt(right)]--;
            right++;

            if (count == dist_count) {
                while (hash[s.charAt(left)] > 1) {
                    if (hash[s.charAt(left)] > 1)
                        hash[s.charAt(left)]--;
                    left++;
                }
                int window = right - left + 1;
                if (min_window > window) {
                    min_window = window;
                    startIndex = left;
                }
            }
        }
        return s.substring(startIndex, startIndex + min_window);
    }

    public static void main(String args[]) {
        Solution ob = new Solution();
        String str = ob.findSubstring("abdacbfcabegbdfcadcefa");
        System.out.println(str);
    }
}

最佳答案

您的算法是正确的,但在实现过程中存在一些问题。 您不应该使用原始字符串中剩余的散列。看下面的代码:

for(int i = 0; i < 256; ++i) hash[i] = 0;  // Before entering while reset hash
                                           // counters for sliding window
while (right < s.length()) {
    if (hash[s.charAt(right)] == 0) {  // Use hash here for counting frequency
        count++;
}
hash[s.charAt(right)]--;  // Consistently increment for right and decrement for left

Working code有上述变化

关于java - 具有原始字符串的所有不同字符的最小长度子字符串的滑动窗口解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708144/

相关文章:

java - 将三维对象存储在一维数组中

java - 应用程序启动时间过长

java - 如何在java中返回过滤后的Hashmap的值?

Java:创建 KML 文件并在现有文件中插入元素

java - 如何对 n 个散列图使用 java 8 合并函数

ruby - 如何将字符串拆分为数组,并保持换行符?

performance - 衡量算法准确性和速度之间的权衡

java - 修剪字符串中的多个字符

algorithm - 装箱任务修改版的最优解

algorithm - 具有轻微约束的数字对的最大唯一性