fky

102 阅读2分钟

算法问题:

1. 给定一个字符串 s 和一个整数 k,保证最多有 k 个重复字母,求出最长的可能结果

这个问题是典型的滑动窗口问题,可以使用滑动窗口来遍历字符串,维护一个窗口内最多包含 k 个不同字符。

算法步骤:

  • 使用一个滑动窗口和哈希表记录窗口内字符的出现次数。
  • 每次更新窗口时,如果当前窗口内的字符数量超过 k,则缩小窗口,直到满足条件。
  • 在遍历的过程中记录窗口的最大长度。
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int longestSubstringWithKRepeatingChars(String s, int k) {
        // 边界条件处理
        if (s == null || s.length() == 0 || k < 1) {
            return 0;
        }
        
        // 使用滑动窗口来处理问题
        int left = 0, right = 0, maxLength = 0;
        Map<Character, Integer> countMap = new HashMap<>();
        
        while (right < s.length()) {
            char c = s.charAt(right);
            // 右指针扩展窗口
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
            
            // 当窗口中的某个字符出现次数超过 k 时,移动左指针收缩窗口
            while (countMap.get(c) > k) {
                char leftChar = s.charAt(left);
                countMap.put(leftChar, countMap.get(leftChar) - 1);
                left++;
            }
            
            // 更新最大长度
            maxLength = Math.max(maxLength, right - left + 1);
            right++;
        }
        
        return maxLength;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "aaabbccc";
        int k = 2;
        int result = solution.longestSubstringWithKRepeatingChars(s, k);
        System.out.println("最长的子串长度是: " + result);
    }
}

2. 字符串 s 进行多次左移和右移操作

给一个字符串s,给一个shit数组[[0,1][1,2]…],其中0表示左移,1表示右移,第一个组合表示左移1位,(abc ->bca)第二个组合表示右移2位,(abc-> bca),写出最后结果

public class StringShift {
    public static void main(String[] args) {
        String s = "abc";
        int[][] shifts = {{0, 1}, {1, 2}};
        String result = applyShifts(s, shifts);
        System.out.println("最终结果是: " + result);
    }

    public static String applyShifts(String s, int[][] shifts) {
        for (int[] shift : shifts) {
            int direction = shift[0];
            int amount = shift[1];
            if (direction == 0) {
                s = leftShift(s, amount);
            } else if (direction == 1) {
                s = rightShift(s, amount);
            }
        }
        return s;
    }

    public static String leftShift(String s, int k) {
        int n = s.length();
        k = k % n; // Handle cases where k > s.length()
        return s.substring(k) + s.substring(0, k);
    }

    public static String rightShift(String s, int k) {
        int n = s.length();
        k = k % n; // Handle cases where k > s.length()
        return s.substring(n - k) + s.substring(0, n - k);
    }
}