重复数字个数倍的字符串
public class Main {
public static void main(String[] args) {
String str = "ab11s3dc1";
String s = fun(str);
System.out.println(s);//abababababababababababsssdc
}
private static String fun(String str) {
String strNum = "", strChars = "", strResult = "";//strNum数字字符串,strChars字母字符串,strResult结果字符串
int len = str.length();
for (int i = 0; i < len; i++) {
if (Character.isDigit(str.charAt(i))) {
//如果是数字
strNum = strNum + str.charAt(i);
} else {
//如果是字母
strChars = strChars + str.charAt(i);
}
if (Character.isDigit(str.charAt(i)) && (i==(len-1)||Character.isDigit(str.charAt(i+1))==false)) {//或运算是短路运算,到最后一个字符时,后部分不会出现空指针
int r = Integer.parseInt(strNum);
for (int j = 0; j < r; j++) {
strResult = strResult + strChars;
}
strNum = "";
strChars = "";
}
}
return strResult;
}
}
输入是某个酒店多个日期段的价格,每个日期段(终止日期大于等于起始日期,终止时间的最大值不会超过1000)和对应的价格使用空格分隔的字符串来表示,比如“0 19 300”,“10 40 250”分别表示从某天开始第1天到第20天价格都是300,第11天到第41天价格都是250,这些日期有可能重复,重复的日期的价格以后面的为准。
请以以下规则合并并输出合并结果:
1、相邻两天的价格如果形同,那么这两天日期段应该合并
2、合并的结果应该以起始日期从小到大排序
输入格式;每个测试输入包含1个测试用例,字符串数组的每个元素占用一行,每行数据间用一个空格分隔,分别表示起始日期、结束日期、价格。
输出格式:每个测试用例的输出为多行,数据间用一个空格分隔(只能用一个空格,否则不给分),分别表示其实日期、结束日期、价格。
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] dataRangePrices=new String[]{"20 30 300","0 19 300","23 40 400","0 10 200","50 55 1000","40 45 400"};
String[] result=baiyi_merge(dataRangePrices);
for(String s:result) {
System.out.println(s);
}
}
private static String[] baiyi_merge(String[] dataRangePrices) {
if(dataRangePrices.length==0){
return new String[]{""};
}
Map map=new HashMap<Integer,Integer>();
List<String> resultList=new ArrayList<String>();
for(String onedata:dataRangePrices){
String[] onePartNumber=onedata.split(" ");
int startDay=Integer.parseInt(onePartNumber[0]);
int endDay=Integer.parseInt(onePartNumber[1]);
int onePrize=Integer.parseInt(onePartNumber[2]);
for(int i=startDay;i<=endDay;i++){
map.put(i,onePrize);
}
}
Set<Map.Entry<Integer, Integer>> sets = map.entrySet();
Iterator<Map.Entry<Integer, Integer>> it=sets.iterator();
Map.Entry<Integer, Integer> onemap=it.next();
int currentStartDay=onemap.getKey();
int currentEndDay=onemap.getKey();
int currentPrize=onemap.getValue();
while(it.hasNext()){
onemap=it.next();
if(onemap.getValue()==currentPrize){
currentEndDay=onemap.getKey();
}else {
resultList.add(currentStartDay+" "+currentEndDay+" "+currentPrize);
currentEndDay=onemap.getKey();
currentStartDay=onemap.getKey();
currentPrize=onemap.getValue();
}
}
resultList.add(currentStartDay+" "+currentEndDay+" "+currentPrize);//输出最后一条
// String[] resultString=new String[resultList.size()];
// for(int i=0;i<resultList.size();i++){
// resultString[i]=resultList.get(i);
// }
// return resultString;
return (String[]) resultList.toArray(new String[0]); //将List转换为字符串数组
}
}