package com.kingdz.algorithm.time201702;import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;/** * 算数表达式分解<br/> * 程序的目的是将:(2+34)*5分解为List,其中分解后的结果为{(,2,+,34,),*,5}<br/> * 依然存在bug,就是分隔符自身含有包含的情况,比如分隔符集合中包含(和((的情况。 * * @author kingdz * */public class Algo03 { /** * 分隔符集合 */ public static final String[] separator = { "(", ")", "[", "]", "{", "}", "+", "-", "*", "/" }; public static void main(String[] args) { String question = "(21+34)*5+12*34"; List<String> result = dismantle(question); System.out.PRintln(Arrays.toString(result.toArray())); } /** * 分解算法 * * @param question * @return */ private static List<String> dismantle(String question) { // 将字符串数组转换为set方便判断 Set<String> separatorSet = new HashSet<String>(); int maxLen = 0; for (String str : separator) { int len = str.length(); if (len > maxLen) { maxLen = len; } separatorSet.add(str); } List<String> ret = new ArrayList<String>(); // 确定开始和结尾来分解字符串 int start = 0; int end = Math.min(start + maxLen, question.length()); while (start < question.length() && start < end) { String sub = question.substring(start, end); // 是否包含分解字符串 if (separatorSet.contains(sub)) { ret.add(sub); start = end; end = Math.min(start + maxLen, question.length()); } else { if (end - start == 1) { if (ret.size() == 0) { // 如果集合为空则直接插入 ret.add(sub); start = end; end = Math.min(start + maxLen, question.length()); } else { // 如果不为空,则需要判断最后一位是否为分隔符 String lastIn = ret.get(ret.size() - 1); if (separatorSet.contains(lastIn)) { ret.add(sub); } else { ret.set(ret.size() - 1, lastIn + sub); } start = end; end = Math.min(start + maxLen, question.length()); } } else { // 将end逐渐较小,保证轮询所有长度的分割字符串数组 end--; } } } return ret; }}
新闻热点
疑难解答