zoukankan      html  css  js  c++  java
  • leetcode 942. DI String Match

    一、算法:

    核心算法非常简单,找规律即可,代码如下:

    char[] arr = S.toCharArray();
    int N = arr.length;
    int[] ans = new int[N+1];	//初始化
    
    int increase = N;
    int decrease = 0;
    for(int i = 0; i < N; i++) {
        if(arr[i] == 'D') {
            ans[i] = increase;
            increase--;
        }
        else {	
            ans[i] = decrease;
            decrease++;
        }
    }
    ans[N] = decrease;
    

    二、结果:

    5 _X%9T{PQOO@@%O8K%_1

    三、一点小建议:

    为了方便调试,笔者有如下建议

    • 使用idea
    • 在src下创建input.txt,并将题干中给出的样例输入写入input.txt
    • 创建Main类
      • 创建main方法
      • 从input.txt读取输入,并调用solution中需要我们实现的方法
      • 将结果输出出来
    • 以本题为例,目录结构&代码如下:

    %C`UFX{ ) KU(ME))24RHTO

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            File f = new File("src/input.txt");
            Scanner scanner = null;
            try {
                scanner = new Scanner(f);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while(scanner.hasNextLine()) {
                int[] ans = new Solution().diStringMatch(scanner.nextLine());
                for(int i = 0; i < ans.length; i++) {
                    System.out.print(ans[i]);
                }
                System.out.println("");
            }
        }
    }
    
    class Solution {
        public int[] diStringMatch(String S) {
            char[] arr = S.toCharArray();
            int N = arr.length;
            int[] ans = new int[N+1];
    
            int increase = N;
            int decrease = 0;
            for(int i = 0; i < N; i++) {
                if(arr[i] == 'D') {
                    ans[i] = increase;
                    increase--;
                }
                else {
                    ans[i] = decrease;
                    decrease++;
                }
            }
            ans[N] = decrease;
            return ans;
        }
    }
    
    
  • 相关阅读:
    一篇文章高效定位iframe
    URL与视图函数的映射
    include标签—引用文件路径
    UnitTest单元测试框架解析【实用篇】
    【案例演练】测试器与模板继承
    2招带你快速获取响应头与发送头
    dede网站如何更新地图sitemap.html
    申请微信小程序流程步骤
    phpstudy本地配置--dede织梦网
    stylus样式开发的使用----vue
  • 原文地址:https://www.cnblogs.com/huangming-zzz/p/10657795.html
Copyright © 2011-2022 走看看