腾讯2020-1 笔试真题

tech2025-12-24  1

题目

腾讯2020-1

腾讯2020-1

/* 小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了, 于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩, 对于字符串中连续的m个相同字符串S将会压缩为[m|S](m为一个整数且1<=m<=100), 例如字符串ABCABCABC将会被压缩为[3|ABC], 现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么? */ package demoProj; import java.util.Collections; import java.util.Scanner; public class TencentXZ2020_1 { 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("]")) { // 检索第一个“]”出现的位置,赋值给right int right = words.indexOf("]"); // 检索最后一个“[”出现的位置到right的位置,赋值给left int left = words.lastIndexOf("[", right); // 将字符串中 left+1 位置到 right 位置的字符添加为子字符串repeatStr String repeatStr = words.substring(left + 1, right); // 将repeatStr字符串中的字符根据符号“|”分隔开,添加到数组split中。 “\\”为转义符 String[] split = repeatStr.split("\\|"); // replace(char oldChar,char newChar); newChar替换掉oldChar words = words.replace("[" + repeatStr + "]", // String.join(",",String[]);在每个元素的间隔添加一个逗号 "," // Collections.nCopies(int n【返回数量】,T o【重复的元素】); 返回结果为n个o。 String.join("", Collections.nCopies(Integer.parseInt(split[0]), split[1]))); } return words; } }

笔记:

words.indexOf() indexOf()方法 words.substring() substring()方法 repeatStr.split() 根据符号分隔字符串;“ \\ ”为转义符。words.replace() 新字符替换旧字符String.join()Collections.nCopies() public static List nCopies(int n, T o) n:返回列表中元素的数量。 o:重复出现在返回列表中的元素。
最新回复(0)