Java 反向编码字符串
我想寻求帮助,了解如何反转我的代码,以便输入“A2B5C2”将给我输出“AABBBCC”,有什么建议吗 谢谢Java 反向编码字符串,java,Java,我想寻求帮助,了解如何反转我的代码,以便输入“A2B5C2”将给我输出“AABBBCC”,有什么建议吗 谢谢 public static void printRLE(String str) { int n = str.length(); for (int i = 0; i < n; i++) { // Count occurrences of current character int count = 1; while (i
public static void printRLE(String str) {
int n = str.length();
for (int i = 0; i < n; i++) {
// Count occurrences of current character
int count = 1;
while (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
// Print character and its count
System.out.print(str.charAt(i));
System.out.print(count);
}
}
public static void main(String[] args) {
String str = "AABBBBBCC";
printRLE(str);
}
publicstaticvoidprintrle(字符串str){
int n=str.length();
对于(int i=0;i
给你:
public static String encode(String input) {
String output = "";
while (true) {
char c = input.charAt(0);
String countStr = "";
char current;
for (int i = 1; i < input.length() && Character.isDigit(current = input.charAt(i)); i++)
countStr += current;
int count = Integer.parseInt(countStr);
for (int i = 0; i < count; i++)
output += c;
int trimLength = 1 + countStr.length();
if (trimLength >= input.length())
return output;
else
input = input.substring(trimLength);
}
}
公共静态字符串编码(字符串输入){
字符串输出=”;
while(true){
字符c=输入字符(0);
字符串countStr=“”;
炭流;
对于(int i=1;i=input.length())
返回输出;
其他的
输入=输入。子字符串(trimLength);
}
}
要得到这个案例,数字将超过9,我建议使用一个简单的正则表达式来匹配字母+数字
,然后只需重复字母所需的次数:
static String getRevRLE(String str) {
StringBuilder res = new StringBuilder();
Matcher m = Pattern.compile("([a-zA-Z][0-9]+)").matcher(str);
while (m.find()) {
String g = m.group();
res.append(g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))));
}
return res.toString();
}
使用Streams
API,您可以将
static String getRevRLE(String str) {
return Pattern.compile("([a-zA-Z][0-9]+)").matcher(str).results()
.map(MatchResult::group)
.map(g -> g.substring(0, 1).repeat(Integer.parseInt(g.substring(1))))
.collect(Collectors.joining());
}
测试
public static void main(String[] args) {
String str = "AABBBBBCCCCCCCCCCCCCCCCCCCC";
String rle = getRLE(str);
String res = getRevRLE(rle);
System.out.println(res + " " + res.equals(str)); // AABBBBBCCCCCCCCCCCCCCCCCCCC true
}
您可以这样执行此任务:
public static String printRLE(String str) {
int n = str.length();
String result = "";
for (int i = 0; i < n - 1; i++) {
char ch = str.charAt(i);
if (!Character.isDigit(ch)) {
if (Character.isDigit(str.charAt(i + 1))) {
int fi = i + 1;
i += 2;
while (i < n && Character.isDigit(str.charAt(i))) i++;
int repeat = Integer.parseInt(str.substring(fi, i));
result += String.valueOf(ch).repeat(repeat);
i--;
} else result += ch;
}
}
return result;
}
public static void main(String[] args) {
String str = "10A10B32C1";
System.out.println(printRLE(str));
}
总是有一个字符,然后是一个数字吗?是的,如果这有帮助的话。太好了,我的答案应该行得通。
AAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBC