问题描述
在广告平台中,为了给广告主一定的自由性和效率,允许广告主在创造标题的时候以通配符的方式进行创意提交。线上服务的时候,会根据用户的搜索词触发的 bidword 对创意中的通配符(通配符是用成对 {} 括起来的字符串,可以包含 0 个或者多个字符)进行替换,用来提升广告投放体验。例如:“{末日血战} 上线送 SSR 英雄,三天集齐无敌阵容!”,会被替换成“帝国时代游戏下载上线送 SSR 英雄,三天集齐无敌阵容!”。给定一个含有通配符的创意和n个标题,判断这句标题是否从该创意替换生成的。
测试样例
样例1:
输入:
n = 4, template = "ad{xyz}cdc{y}f{x}e", titles = ["adcdcefdfeffe", "adcdcefdfeff", "dcdcefdfeffe", "adcdcfe"]
输出:"True,False,False,True"
样例2:
输入:
n = 3, template = "a{bdc}efg", titles = ["abcdefg", "abefg", "efg"]
输出:"True,True,False"
样例3:
输入:
n = 5, template = "{abc}xyz{def}", titles = ["xyzdef", "abcdef", "abxyzdef", "xyz", "abxyz"]
输出:"True,False,True,True,True"
方法一:模拟法
import java.util.ArrayList;
import java.util.List;
public class Main {
public static String solution(int n, String template_, String[] titles) {
// Please write your code here
StringBuilder sb = new StringBuilder();
for(String title : titles){
if(isTrue(title,template_)){
sb.append("True");
}else{
sb.append("False");
}
sb.append(",");
}
return sb.substring(0,sb.length()-1);
}
private static boolean isTrue(String title, String template_) {
List<String> list = new ArrayList<>();
int index = 0;
StringBuilder sb = new StringBuilder();
while (index < template_.length()){
if(template_.charAt(index) == '{'){
index++;
if(sb.length() != 0){
list.add(sb.toString());
sb = new StringBuilder();
}
while (template_.charAt(index) != '}') index++;
}else{
sb.append(template_.charAt(index));
}
index++;
}
if(sb.length() != 0) list.add(sb.toString());
int index_title = 0;
for(String s : list){
int i = 0;
while (i < s.length() && index_title < title.length()){
if(s.charAt(i) != title.charAt(index_title)){
i = 0;
}else{
i++;
}
index_title++;
}
if(i != s.length()) return false;
}
if(template_.startsWith("{") && template_.endsWith("}")){
return true;
}else if(template_.startsWith("{")){
return title.endsWith(list.get(list.size()-1));
}else if(template_.endsWith("}")){
return title.startsWith(list.get(0));
}else{
return title.startsWith(list.get(0)) && title.endsWith(list.get(list.size()-1));
}
}
public static void main(String[] args) {
// You can add more test cases here
String[] testTitles1 = {"adcdcefdfeffe", "adcdcefdfeff", "dcdcefdfeffe", "adcdcfe"};
String[] testTitles2 = {"CLSomGhcQNvFuzENTAMLCqxBdj", "CLSomNvFuXTASzENTAMLCqxBdj", "CLSomFuXTASzExBdj", "CLSoQNvFuMLCqxBdj", "SovFuXTASzENTAMLCq", "mGhcQNvFuXTASzENTAMLCqx"};
String[] testTitles3 = {"abcdefg", "abefg", "efg"};
System.out.println(solution(4, "ad{xyz}cdc{y}f{x}e", testTitles1).equals("True,False,False,True"));
System.out.println(solution(6, "{xxx}h{cQ}N{vF}u{XTA}S{NTA}MLCq{yyy}", testTitles2).equals("False,False,False,False,False,True"));
System.out.println(solution(3, "a{bdc}efg", testTitles3).equals("True,True,False"));
}
}