这是一个自我思考的小测验,非常类似于我面临的现实生活问题。
假设我有一个字符串列表(假设它被称为stringlist
),其中一些字符串的末尾附加了两位数字例如,“foo”,“foo01”,“foo24”。
我想用相同的字母(但结尾用不同的两位数字)对它们进行分组。
所以,“foo”、“foo01”和“foo24”都属于“foo”组。
但是,我不能只检查以“foo”开头的字符串,因为我们还可以有“food”、“food08”、“food42”。
没有副本。
中间有数字是可能的。“foo543food43”在“foo543food”组下
或者在结尾处有多个数字。Ex)“foo1234”在“foo12”组下
我能想到的最明显的解决办法是列一张数字表。
numbers = ["0", "1", "2", ... "9"]
那么,我会的
grouplist = [[]] //Of the form: [[group_name1, word_index1, word_index2, ...], [group_name2, ...]]
for(word_index=0; word_index < len(stringlist); word_index++) //loop through stringlist
for(char_index=0; char_index < len(stringlist[word_index]); char_index++) //loop through the word
if(char_index == len(stringlist[word_index])-1) //Reached the end
for(number1 in numbers)
if(char_index == number1) //Found a number at the end
for(number2 in numbers)
if(char_index-1 == number2) //Found another number one before the end
group_name = stringlist[word_index].substring(0,char_index-1)
for(group_element in grouplist)
if(group_element[0] == group_name) //Does that group name exist already? If so, add the index to the end. If not, add the group name and the index.
group_element.append(word_index)
else
group_element.append([stringlist[word_index].substring(0,char_index-1), word_index])
break //If you found the first number, stop looping through numbers
break //If you found the second number, stop looping through numbers
现在看起来一团糟你们能想到更干净的方法吗?
包括最终结果在内的任何数据结构都可以是您想要的。
最佳答案
我将创建一个映射,将组名映射到对应组的所有字符串的列表。
这里是我在Java中的方法:
public Map<String, List<String>> createGroupMap(Lust<String> listOfAllStrings){
Map<String, List<String>> result= new Hashmap<>();
for(String s: listOfAllStrings){
addToMap(result, s)
}
}
private addToMap(Map<String, List<String>> map, String s){
String group=getGroupName(s);
if(!map.containsKey(group))
map.put(group,new ArrayList<String>();
map.get(group).add(s);
}
private String getGroupName(String s){
return s.replaceFirst("\\d+$", "");
}
也许您可以通过避免
getGroupName(..)
中的RegExp来获得一些速度,但是您需要对其进行分析,以确保没有RegExp的实现会更快。关于algorithm - 过滤字符串末尾带数字的最有效方法是什么(例如foo12)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41218220/