【算法】程序猿不写代码是不对的13
2017-02-07 21:09
495 查看
package com.kingdz.algorithm.time201702; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * 算数表达式分解<br/> * 程序的目的是将:(2+34)*5分解为List,其中分解后的结果为{(,2,+,34,),*,5}<br/> * * @author kingdz * */ public class Algo07 { /** * 分隔符集合 */ 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 */ static List<String> dismantle(String question) { // 将字符串数组转换为set方便判断 List<String> separatorList = new ArrayList<String>(); int maxLen = 0; for (String str : separator) { int len = str.length(); if (len > maxLen) { maxLen = len; } separatorList.add(str); } Collections.sort(separatorList, new Comparator<String>() { public int compare(String o1, String o2) { if (o1 == null || o2 == null) { return 0; } return o2.length() - o1.length(); } }); 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 (separatorList.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 (separatorList.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; } }
相关文章推荐
- 【算法】程序猿不写代码是不对的2
- 【算法】程序猿不写代码是不对的5
- 【算法】程序猿不写代码是不对的26
- 【算法】程序猿不写代码是不对的32
- 【算法】程序猿不写代码是不对的31
- 【算法】程序猿不写代码是不对的36
- 【算法】程序猿不写代码是不对的22
- 【算法】程序猿不写代码是不对的21
- 【算法】程序猿不写代码是不对的34
- 【算法】程序猿不写代码是不对的6
- 【算法】程序猿不写代码是不对的12
- 【算法】程序猿不写代码是不对的11
- 【算法】程序猿不写代码是不对的24
- 【算法】程序猿不写代码是不对的18
- 【算法】程序猿不写代码是不对的3
- 【算法】程序猿不写代码是不对的10
- 【算法】程序猿不写代码是不对的15
- 【算法】程序猿不写代码是不对的29
- 【算法】程序猿不写代码是不对的35
- 【算法】程序猿不写代码是不对的20