//输入一个字符串,字符串中包含了全量字符集和已占用字符集,两个字符集用@相连。
//@前的字符集合为全量字符集,@后的字符集为已占用字符集合。
//已占用字符集中的字符一定是全量字符集中的字符。
//字符集中的字符跟字符之间使用英文逗号分隔。
//字符集中的字符表示为字符加数字,字符跟数字使用英文冒号分隔,比如a:1,表示1个a字符。
//字符只考虑英文字母,区分大小写,数字只考虑正整形,数量不超过100,如果一个字符都没被占用,@标识符仍在,例如a:3,b:5,c:2@
//输入:a:3,b:5,c:2@a:1,b:2
//输出:a:2,b:3,c:2
//说明:全量字符集为3个a,5个b,2个c。已占用字符集为1个a,2个b。由于已占用字符集不能再使用,因此,剩余可用字符为2个a,3个b,2个c。因此输出a:2,b:3,c:2。注意,输出的字符顺序要跟输入一致。不能输出b:3,a:2,c:2。如果某个字符已全被占用,不需要输出。例如a:3,b:5,c:2@a:3,b:2,输出为b:3,c:2。
python实现:
def main():
s = input()
stringArr = s.strip().split("@")
s = OperationString(stringArr) # 把字符串分割成2个部分
print(s)
def OperationString(stringArr): # 返回字符串
i = 0
wordCount = {}
for s in stringArr:
putDir(s, i, wordCount)
i += 1
s=''
count = len(wordCount.keys())
for item in wordCount.keys():
count -= 1
if wordCount[item] != 0:
if count > 0:
s += (item+":"+str(wordCount[item])+",")
else:
s += (item + ":" + str(wordCount[item]))
return s
def putDir(s, flag, wordCount):
chNumlst = s.split(",")
for item in chNumlst:
lst = item.split(":")
ch = lst[0]
num = eval(lst[1])
if flag != 1:
wordCount[ch] = num
else:
if wordCount.get(ch) != None:
temp = wordCount[ch]
wordCount[ch] = temp - num
else:
wordCount[ch] = num
main()
java实现
import java.util.*;
public class 华为面试题一 {
public static void main(String []args){
String str =new Scanner(System.in).nextLine();
String []strs = str.split("@");
str= OperationString(strs);
System.out.println(str);
}
public static String OperationString(String[] strs){
if(strs.length==1) return strs[0];
Map<String ,Integer> map=new HashMap<>();
int flag=0;
for(String str :strs){
map = putMap(map,str,flag++);
}
//把字符串重新组合
StringBuffer buf=new StringBuffer();
for(String key : map.keySet()){
if(map.get(key)!=0){
buf.append(key+":"+map.get(key)+",");
}
}
String str=buf.toString();
return str.substring(0,str.length()-1);
}
public static Map<String,Integer>putMap(Map<String,Integer>map,String str,int flag){
String [] strs=str.split(",");
for(String s:strs){
String s1=s.split(":")[0];
int num= Integer .parseInt(s.split(":")[1]);
if(flag ==1 && map.containsKey(s1)){//表示的是已经占用
int temp=map.get(s1)-num;
map.put(s1,temp);
}else{
map.put(s1,num);
}
}
return map;
}
}