题目
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. 完成这个解决方案,这样它就可以去掉所有跟在传入的一组注释标记后面的文本。行尾的任何空格也应该去掉
例子
Given an input string of: apples, pears # and bananas grapes bananas !apples The output expected would be: apples, pears grapes bananas The code would be called like so: var result = solution(“apples, pears # and bananas\ngrapes\nbananas !apples”, [“#”, “!”]) // result should == “apples, pears\ngrapes\nbananas”
分析
字符串操作的问题优先考虑能不能用正则表达式做,这题利用正则表达式完成比较简单。首先确定匹配规则 任意个空格加上给的注释标记符号后任意个字符 翻译成正则表达式就是 [ ]*([给定字符].*)?$ ,然后就是根据 \n 对原始文本进行切分,最后统一拼接的时候在后面加上 \n 就可以了。当然使用 Stream 操作可以简化代码,同时并行加快运算效率。
我的解法
import java.util.Arrays;import java.util.stream.Collectors;public class StripComments {public static String stripComments(String text, String[] commentSymbols) {String regex = String.format("[ ]*([%s].*)?$",Arrays.stream(commentSymbols).collect( Collectors.joining())) ;return Arrays.stream(text.split("\n")).map(x -> x.replaceAll(regex, "")).collect(Collectors.joining("\n"));}}
参考解法
import java.util.Arrays;import java.util.stream.Collectors;public class StripComments {public static String stripComments(String text, String[] commentSymbols) {String pattern = String.format("[ ]*([%s].*)?$",Arrays.stream( commentSymbols ).collect( Collectors.joining() ));return Arrays.stream( text.split( "\n" ) ).map( x -> x.replaceAll( pattern, "" ) ).collect( Collectors.joining( "\n" ) );}}
提升
- 利用正则表达式可以提高效率
- Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)
