日期:2014-05-20 浏览次数:20814 次
import java.util.ArrayList; import java.util.List; /** * * @author cstur4 * */ public class CSDN { public static void main(String[] args) { String mode = "111100111111100011111011"; List<String> res = conversionMode(mode); for(String s:res) System.out.println(s); } public static List<String> conversionMode(String mode){ List<String> res = new ArrayList<String>(); int index = 0; while(index<mode.length()){ if(mode.charAt(index)=='1'){ int end = getRightIndex(mode, index); String newMode = fillWith0(index)+"-"+fillWith0(end); res.add(newMode); index = end+1; }else index++; } return res; } private static int getRightIndex(String mode, int index) { while(index<mode.length() && mode.charAt(index)=='1') ++index; return index-1; } private static String fillWith0(int num){ String value = String.valueOf(num); if(value.length()==1) return "0"+num; return value; } }
------解决方案--------------------
public static void main(String args[]) { List<String> list = new ArrayList<String>(); String mode = "111100111111100011111011"; char[] data = mode.toCharArray(); int startIndex = -1; int endIndex = -1; for (int i = 0; i < data.length; i++) { if (data[i] == '1') { if (startIndex == -1) { if(i == data.length - 1){ String tempStart = ("00"+i).replaceAll(".*?(\\d{2})$", "$1"); String tempEnd = ("00"+i).replaceAll(".*?(\\d{2})$", "$1"); list.add(tempStart + "-" + tempEnd); startIndex = -1; endIndex = -1; } else{ startIndex = i; endIndex = i; } } else { if(i == data.length - 1){ String tempStart = ("00"+startIndex).replaceAll(".*?(\\d{2})$", "$1"); String tempEnd = ("00"+i).replaceAll(".*?(\\d{2})$", "$1"); list.add(tempStart + "-" + tempEnd); startIndex = -1; endIndex = -1; } else{ endIndex = i; } } } if (data[i] == '0') { if (startIndex != -1) { String tempStart = ("00"+startIndex).replaceAll(".*?(\\d{2})$", "$1"); String tempEnd = ("00"+endIndex).replaceAll(".*?(\\d{2})$", "$1"); list.add(tempStart + "-" + tempEnd); startIndex = -1; endIndex = -1; } } } System.out.println(list); }