java笔试题--Java实现命令编辑器

题目:假定有一命令编辑框,可以接受两种命令:【type x】和【undo n】。x代表输入文本,n代表秒数。type命令用于当输入文本,而undo命令用于撤销操作。输入undo 1,表示向前撤销1秒。撤销操作可以指定撤销到当前时间之前操作的时间,并且撤销操作对自身同样有效。

例子:

命令输入的时间命令显示结果
1type aa
2type bab
3type cabc
4undo 1ab
5undo 1a

实现代码如下:

package javatest;

import java.util.HashMap;
import java.util.Map;

class CmdException extends RuntimeException {

	
	private static final long serialVersionUID = 8562504939570096319L;

	public CmdException() {
		super();
	}

	public CmdException(String message, Throwable cause) {
		super(message, cause);
	}

	public CmdException(String message) {
		super(message);
	}

	public CmdException(Throwable cause) {
		super(cause);
	}

}

/**
 * @author NiluChen
 *
 */
public class CommandEditor {

	private static final String TYPE_PATTERN = "\\s*(type|TYPE)\\s+\\w+\\s*";
	private static final String UNDO_PATTERN = "\\s*(undo|UNDO)\\s+\\d+\\s*";

	/**
	 * 
	 * @param cmds 命令
	 * @param times 时间点
	 * @return String 返回结果
	 * @throws IllegalArgumentException
	 */
	public static String cmdEditor(String[] cmds, int[] times)
			throws IllegalArgumentException {
		// 使用map缓存了每次操作后的时间点和结果
		Map<Integer, String> resultBuffer = new HashMap<Integer, String>();
		// 文本内容
		String text = "";
		for (int i = 0; i < cmds.length; i++) {
			String cmd = cmds[i].trim();
			if (cmd.matches(CommandEditor.TYPE_PATTERN)) {
				String[] strs = cmd.split("\\s+");
				text += strs[1];
				resultBuffer.put(times[i], text);
			} else if (cmd.matches(CommandEditor.UNDO_PATTERN)) {
				int undoTime = Integer.parseInt(cmd.split("\\s+")[1]);
				if (undoTime > times[i])
					throw new CmdException("参数不合法!");
				// 撤销时间点
				int rollbackTime = times[i] - undoTime - 1;
				// 执行撤销
				while (!resultBuffer.containsKey(rollbackTime))
					rollbackTime--;
				resultBuffer.put(times[i], resultBuffer.get(rollbackTime));
			} else
				throw new CmdException("参数不合法!");
		}
		return resultBuffer.get(times[times.length - 1]);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		String[] cmds = { "type a", "type btg", "type c", "undo 1", "undo 2" };
		int[] times = { 1, 2, 3, 4, 5 };
		String result = CommandEditor.cmdEditor(cmds, times);
		System.out.println(result);
		System.out.println(result.equals("abtg"));
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值