问题描述:给你一个字符串licensePlate,字符串中包含大小写字母,空格,数字。判断字符串数组words中,哪个字符串包含了licensePlate中所有的字母(大小写不敏感).
思路:将licensePlate预处理,全部转换为小写,去除数字,空格。然后对出现的字母进行统计。随后遍历words中每个字符串。根据之前的记录判断字符串是否包含所有的字母。
原答案:
public String shortestCompletingWord(String licensePlate, String[] words) {
licensePlate=licensePlate.toLowerCase();
int length=licensePlate.length();
char[] charArray=new char[length];
int position=0;
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<length;i++){
char chr=licensePlate.charAt(i);
if((chr>='A'&&chr<='Z')||(chr>='a'&&chr<='z')){
if(map.containsKey(chr)){
map.put(chr,map.get(chr)+1);
}else{
charArray[position]=chr;
map.put(chr,1);
position++;
}
}
}
licensePlate=new String(charArray);
licensePlate=licensePlate.trim();
int checkLenth=licensePlate.length();
int wordsLength=words.length;
String[] result=new String[wordsLength];
int resPos=0;
for(int j=0;j<wordsLength;j++){
int count=0;
Map<Character,Integer> temp=new HashMap<Character,Integer>(map);
String word=words[j];
length=word.length();
for(int k=0;k<length;k++){
char c=word.charAt(k);
if(temp.containsKey(c)&&temp.get(c)>0){
temp.put(c, temp.get(c)-1);
}
}
for(int k=0;k<checkLenth;k++){
count=count+(temp.get(licensePlate.charAt(k)));
}
if(count==0){
result[resPos]=word;
resPos++;
}
}
int minLength=1000;
resPos=0;
for(int j=0;j<wordsLength;j++){
String word=result[j];
if(word!=null){
int workLength=word.length();
if(workLength>0&&workLength<minLength){
minLength=word.length();
resPos=j;
}
}
}
return result[resPos];
}
仓促下写成,最佳答案待补完