Назначение состоит в распаковке строки. В частности, код должен работать для 3 образцов, как показано на рисунке. Декомпрессировать строку с большим количеством вложенных строк
Мой код здесь работает в первых двух образцах. Однако я не могу придумать третий образец. Вероятно, я не понял, вероятно, понятие рекурсии. Вы можете мне помочь?
import java.util.Scanner;
public class Compression4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input=in.next();
System.out.println(uncompress(input));
}
public static boolean flag = true;
public static String uncompress(String compressedText)
{
return uncompress(compressedText, "", "");
}
public static String getMultiple(String x, int N) {
if (N == 0) return "";
return ""+x+getMultiple(x,N-1);
}
public static String uncompress(String text, String count, String output)
{
if (text.equals(""))
{
return output;
}
if(text.charAt(0) == '(')
{
int FirstIndex = text.indexOf("(")+1;
String inner = text.substring(FirstIndex, text.lastIndexOf(")"));
//System.out.println(inner);
flag = false;
return uncompress (inner, count, output);
}
else if (Character.isLetter(text.charAt(0)))
{
//letter case - need to take the count we have accrued, parse it into an integer and add to output
if (flag==true)
{
//System.out.println(count);// * text.charAt(0);
String s = String.valueOf(text.charAt(0));
output += getMultiple(s,Integer.parseInt(count));
count ="1";
}
else
{
//System.out.println(count);// * text.charAt(0);
output += getMultiple(text,Integer.parseInt(count));
//System.out.println("output: "+output);
count="0";
}
}
else if(Character.isDigit(text.charAt(0)))
{
//digit case - need to add to the count but keep as a string because must be parsed later
if(flag)
count += (""+text.charAt(0));
else
{
count = "0";
count += (""+text.charAt(0));
}
}
//parse the *remainder* of the string, one character at a time, so pass in the substring(1)
return uncompress(text.substring(1), count, output);
}
}
Это хорошее задание! Но только у вас есть три образца? – Aris2World
Я добавлю еще несколько инструкций –
Как можно понять из этих примеров, мы предполагаем, что число 11 в строке 11ab указывает, что следующий символ a повторяется 11 раз. Если мы хотим, чтобы более длинный шаблон повторялся, используйте круглые скобки: номер 4 в строке4 (ab) указывает, что подстрока ab повторяется 4 раза. Все несжатые строки состоят только из двух символов a и b. Хотя сжатые строки также могут содержать числа и круглые скобки, как в приведенных выше примерах. –