学习内容

滑动窗口LeeCodeJava

1208.尽可能使字符串相等

我的代码

  1. class Solution {
  2. public int equalSubstring(String s, String t, int maxCost) {
  3. int res=0;
  4. int left=0;
  5. int right;
  6. int count=0;
  7. for (right = 0; right < t.length(); right++) {
  8. int def=calculateTheDifference(s.charAt(right),t.charAt(right));
  9. maxCost-=def;
  10. if(def<=maxCost){
  11. count++;
  12. }else{
  13. if(count>res){
  14. res=count;
  15. }
  16. count++;
  17. while(maxCost<0){
  18. maxCost+=calculateTheDifference(s.charAt(left),t.charAt(left));
  19. left++;
  20. count--;
  21. }
  22. }
  23. }
  24. if(count>res){
  25. res=count;
  26. }
  27. return res;
  28. }
  29. int calculateTheDifference(int a,int b){
  30. return Math.abs(a-b);
  31. }
  32. }

思路:

使用滑动窗口的思想,使用双指针的方法,右指针一查到底,左指针会当maxCount处于负数的时候,则将左指针向右移动,缩小窗口,直到MaxCount重新达到0以上(即合法).随后,当窗口再次合法后稳定了.计算窗口的大小,如果窗口的大小,超过了目前已知的最大的窗口大小,就刷新窗口的最大值.不要忘记,在最后尝试刷新一下最大窗口的大小.

优解大小

  1. class Solution {
  2. public int equalSubstring(String s, String t, int maxCost) {
  3. int n = s.length();
  4. int[] diff = new int[n];
  5. for (int i = 0; i < n; i++) {
  6. diff[i] = Math.abs(s.charAt(i) - t.charAt(i));
  7. }
  8. int maxLength = 0;
  9. int start = 0, end = 0;
  10. int sum = 0;
  11. while (end < n) {
  12. sum += diff[end];
  13. while (sum > maxCost) {
  14. sum -= diff[start];
  15. start++;
  16. }
  17. maxLength = Math.max(maxLength, end - start + 1);
  18. end++;
  19. }
  20. return maxLength;
  21. }
  22. }

心得

1.如果要计算的话,可以把循环里面的给拆开来,就比如这里的循环中每个位置都需要计算一下,可以用一个循环来单独计算一下.
2.在这个循环中省略了count的技术,减少了循环的计算.进而减少运算时间.
3.思路差不多,以这个为主.