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;
    }
}

原文地址:https://www.cnblogs.com/huangming-zzz/p/10657795.html