问题:
给定输入字符串如“1,2,3..6..8,9..11”,我们必须将其转换为“1,2,3,4,5,6,7,8, 9,10,11" 。所以基本上我们必须填充点所提到的范围。以下是我的解决方案。有没有更好的方法来解决这个问题?我们可以进一步优化吗?
public class FlattenAString {
public static String flattenAString(String input) {
StringBuilder sbr = new StringBuilder("");
StringBuilder current = new StringBuilder("");
StringBuilder next = new StringBuilder("");
int i = 0;
while (i < input.length()) {
if (input.charAt(i) == '.') {
i = i + 2;
while (i != input.length() && input.charAt(i) != '.' && input.charAt(i) != ',') {
next.append(input.charAt(i));
i++;
}
int currentInt = Integer.parseInt(current.toString());
int nextInt = Integer.parseInt(next.toString());
appendFromCurrentTillPrevToNextInt(currentInt, nextInt, sbr);
current = next;
next = new StringBuilder("");
} else if (input.charAt(i) == ',') {
sbr.append(current);
sbr.append(',');
current = new StringBuilder("");
i++;
} else {
current.append(input.charAt(i));
i++;
}
}
sbr.append(current);
return sbr.toString();
}
private static void appendFromCurrentTillPrevToNextInt(int current, int val, StringBuilder sbr) {
for (int i = current; i < val; i++) {
sbr.append(i);
sbr.append(',');
}
}
}
答案 0 :(得分:0)
我会通过将输入字符串拆分两次来实现此目的。首先,用逗号分割以获得带有省略号的单个数字或范围。对于单个数字,只需将它们添加到列表中即可。对于范围,请在..
上执行第二次拆分以获取另一个数字列表。然后迭代这些对中的每一对的范围以填充缺失的值。
注意这里有一个棘手的问题是我们需要避免重复计算范围内的数字位置。最好通过示例解释:
3..6..8
对于此范围,我们首先添加3, 4, 5, 6
。但对于第二个省略号,我们从 7 开始,然后继续直到点击8
。
String input = "1,2,3..6..8,9..11";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();
for (String part : parts) {
if (!part.contains("..")) {
list.add(Integer.parseInt(part));
}
else {
String[] ranges = part.split("\\.\\.");
for (int i=0; i < ranges.length-1; ++i) {
int start = Integer.parseInt(ranges[i]) + (i == 0 ? 0 : 1);
int end = Integer.parseInt(ranges[i+1]);
for (int j=start; j <= end; ++j) list.add(j);
}
}
}
// print list of numbers
for (int i=0; i < list.size(); ++i) {
System.out.print((i > 0 ? ", " : "") + list.get(i));
}
<强>输出:强>
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
在这里演示:
答案 1 :(得分:0)
试试这个。
static final Pattern RANGE = Pattern.compile("(\\d+)(\\.\\.(\\d+))+");
static String flattenString(String input) {
StringBuffer sb = new StringBuffer();
StringBuilder temp = new StringBuilder();
Matcher m = RANGE.matcher(input);
while (m.find()) {
int begin = Integer.parseInt(m.group(1));
int end = Integer.parseInt(m.group(3));
temp.setLength(0);
for (int i = begin; i <= end; ++i)
temp.append(",").append(i);
m.appendReplacement(sb, temp.substring(1));
}
m.appendTail(sb);
return sb.toString();
}