每日一题 为了工作 2020 0331 第二十九题

/**
*
* 问题:判断两个字符串是否为变形词
* 给定两个字符串str1和str2, 如果str1和str2中出现的字符种类一样且每种字符出现
* 的次数也一样,那么 str1与 str2互为变形词。
*
* 举例:
* str1 = " 123", str2="231", 返回 true。
* str1 = "123", str2="2331", 返回 false。
*
* 解答:
* 如果字符串 str1和 str2长度不同, 直接返回 false 。如果长度相同, 假设出现字符的
* 编码值在 0-255之间, 那么先申请一个长度为256的整型数组 map, map[a]=b代表字符编码为
* a的字符出现了 b次, 初始时 map[0 .. 255]的值都是 0。然后遍历字符串 str1, 统计每种字
* 符出现的数量, 比如遍历到字符 'a', 其编码值为97, 则令 map[97]++。这样 map就成了str1
* 中每种字符的词频统计表。然后遍历字符串str2, 每遍历到一个字符都在 map中把词频减下来, 比
* 如遍历到字符 'a', 其编码值为 97, 则令 map[97]--, 如果减少之后的值小于O, 直接返回false。
* 如果遍历完str2, map中的值也没出现负值, 则返回true。
*
*
* @author 雪瞳
*
*/

*代码

public class IsDeformation {
	
	public boolean getIsDeformation(String a , String b){
		
		if(a.length()!=b.length() || a==null || b==null){
			return false;
		}
		//将字符串转化为字符数组
		char cha1[] = a.toCharArray();
		/**
		 * test
		 */
//		System.out.println("初始字符数组");
//		for(char x :cha1){
//			System.out.print(x+"\t");
//		}
		char cha2[] = b.toCharArray();
		int map[] = new int[256];
//		System.out.println("\n初始 map数组");
//		for(int x:map){
//			System.out.print(x+"\t");
//		}
		for(int i=0;i<cha1.length;i++){
			map[cha1[i]]++;
		}
//		System.out.println("\n遍历结束 map数组");
//		for(int x:map){
//			System.out.print(x+"\t");
//		}
//		System.out.println();
		for(int i=0;i<cha2.length;i++){
			map[cha2[i]]--;
			if(map[cha2[i]]<0){
				return false;
			}
		}
		
		return true;
	}
}

  

public class TestIsDeformation {
	
	public static void main(String[] args) {
		TestIsDeformation test = new TestIsDeformation();
		IsDeformation  idf = new IsDeformation();
		boolean result = false;
		String a = "12321";
		String b = "11223";
		String c = "abcd";
		String d = "abcc";
		result = idf.getIsDeformation(a, b);
		test.showResult(result);
		
		result = idf.getIsDeformation(c, d);
		test.showResult(result);
	}
	public void showResult(boolean flag){
		if(flag){
			System.out.println("互为变形词");
		}else{
			System.out.println("不是互为变形词");
		}
	}
}

  

*运行结果

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12604305.html