#2020、4、19学习,关于字符串的一些方法
压缩算法
对于字符串中连续的m个相同字符串S将会压缩为m|S,例如字符串ABCABCABC将会被压缩为[3|ABC],现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么?
链接:https://www.nowcoder.com/questionTerminal/c27561e5b7e0441493adb9a54071888d?f=discussion
来源:牛客网
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
scanner.close();
System.out.println(decode(next));
}
public static String decode(String words){
while (words.contains("]")){
int right = words.indexOf("]");
int left = words.lastIndexOf("[", right);
String repeatStr = words.substring(left+1, right);
String[] split = repeatStr.split("\\|");
words = words.replace("["+repeatStr+"]",
String.join("", Collections.nCopies(Integer.parseInt(split[0]), split[1])));
}
return words;
}
1.java.util.Collections.ncopies()方法
public static List nCopies(int n, T o)
n-- 在返回列表中元素的个数。
o-- 在返回列表中反复出现的元素
方法调用返回的不可变列表组成的n个拷贝的指定对象。
2.**Integer.parseInt(String)**就是将String字符类型数据转换为Integer整型数据。
3.**String.join(char a,T elements)**方法,简单理解就是在每个元素后面加符号a,除了最后一个。
4.public String replace(char oldChar,char newChar)
用 newChar 字符替换字符串中出现的所有 oldChar 字符,并返回替换后的新字符串。