算法(三十三)
1、判定字符串B是否可由字符串A变换的来 比如 “abccd” “acbcd” 可以。
public boolean fun(String a, String b){
int len1 = a.length();
int len2 = b.length();
HashMap<String> hm1 = new HashMap<String>;
HashMap<String> hm2 = new HashMap<String>;
boolean flag = true;
if(len1 != len2) (return false;}
for(int i=0; i<len1; i++){
if(!hm1.containsKey(a.charAt(i))){
hm1.put(a.charAt(i), 1);
}else{
val = hm1.get(a.charAt(i));
hm1.put(a.charAt(i), ++val);
}
}
for(int i=0; i<len2; i++){
if(!hm2.containsKey(b.charAt(i))){
hm2.put(b.charAt(i), 1);
}else{
val = hm2.get(b.charAt(i));
hm2.put(b.charAt(i), ++val);
}
}
for(int i=0; i<len1; i++){
if(hm1.containsKey(b.charAt(i)) && (hm1.get(b.charAt(i)) == hm2.get(b.charAt(i)))){
continue;
}else{
flag = false;
break;
}
}
return flag;
}
2.给定形如pattern="aabbc",city="北京 北京 上海 上海 蓬莱"两个字符串,这样的pattern和city之间是匹配的(a=北京,b=上海,c=蓬莱)。规定pattern内的字符属于[a-z],city的城市名必定以空格分隔,给定任意pattern和city,返回它们是否匹配(True/False)
public class test002 {
private static boolean fun1(String pattern, String city) {
HashMap<Character, String> hm = new HashMap<>();
String[] new_city = city.split(" ");
int len1 = pattern.length();
int len2 = new_city.length;
boolean flag = false;
if(len1 != len2) return false;
for(int i=0; i<len1; i++){
hm.put(pattern.charAt(i), new_city[i]);
}
for(int i=0; i<len1; i++){
if(hm.get(pattern.charAt(i)).equals(new_city[i])){
flag=true;
}else{
flag=false;
break;
}
}
return flag;
}
private static boolean fun2(String city, String pattern) {
HashMap<String, Character> hm = new HashMap<>();
String[] new_city = city.split(" ");
int len1 = pattern.length();
int len2 = new_city.length;
boolean flag = false;
if(len1 != len2) return false;
for(int i=0; i<len1; i++){
hm.put(new_city[i], pattern.charAt(i));
}
for(int i=0; i<len1; i++){
if(hm.get(new_city[i]).equals(pattern.charAt(i))){
flag=true;
}else{
flag=false;
break;
}
}
return flag;
}
public static void main(String[] args) {
String pattern= "aabbc";
String city = "北京 北京 上海 上海 蓬莱";
boolean flag1 = fun1(pattern, city);
boolean flag2 = fun2(city, pattern);
if(flag1 && flag2) System.out.println(true);
else{
System.out.println(false);
}
}
}
根据自己所见所闻进行算法归纳总结