确定两字符串乱序同构

给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。 这里规定大小写为不同字符,且考虑空格。

算法思路

用两个数组分别统计字符串中每个字符出现的次数,如果所有的字符出现的次数都相同,就是同构的字符串。

代码实现

public class Same {
	public boolean checkSam(String stringA, String stringB) {
        // 首先判断两个字符串长度是否相等,不相等返回false
			int lenA = stringA.length();
			int lenB = stringB.length();
			if(lenA != lenB){
				return false;
			}
			//新建两个数组,保存每个字符出现的次数
			int[] strA = new int[256];
			int[] strB = new int[256];
			for(int i = 0; i < lenA; i++){
				strA[stringA.charAt(i)]++;
				strB[stringB.charAt(i)]++;
			}
			//比较每个字符出现的次数,又不相同的就返回false
			for(int i = 0;i<256;i++){
				if(strA[i]!=strB[i]){
				return false;
			}
		}
			return true;
    }
}
``
posted @ 2017-08-15 16:07  Lee_Shuai  阅读(566)  评论(0)    收藏  举报