【程序员面试经典】确定两串乱序同构。

程序员面试经典

题目要求

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

给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。

核心思想

方法1.先排序,后一一对比。
方法2.用ASCII码值进行对比

完整代码如下(从牛客经典的Github链接上抄下来的一篇优秀代码,自己写的有点low)

public class question_3 {	
//方法1.先排序,后对比。
	public static String sort(String s) {
		char[] content = s.toCharArray();
		java.util.Arrays.sort(content);
		return new String(content);
	}
	
	public static boolean permutation(String s, String t) {
		return sort(s).equals(sort(t));
	}
//方法2.
	public static boolean anagram(String s, String t) {
		if (s.length() != t.length())
			return false;
		int[] letters = new int[128];
		//建立128个元素的数组,int的默认值为0
		int num_unique_chars = 0;
		int num_completed_t = 0;
		char[] s_array = s.toCharArray();
		for (char c : s_array) { // count number of each char in s.
			if (letters[c] == 0)
				++num_unique_chars;//如果这个ASCII第一次出现,则加到num_unique_chars里.
			++letters[c];//找到对应ASCII码值,数量加1,即当前ASCII码值的数的数量加1;
		}
		for (int i = 0; i < t.length(); ++i) {
			int c = (int) t.charAt(i);
			if (letters[c] == 0) { // Found more of char c in t than in s.即如果当前B数组里有的字符的ASICC值在数组A没有出现过,那么就确定B中有A中没有的字符;
				return false;
			}
			--letters[c];//当前元素数量减1
			if (letters[c] == 0) {
				++num_completed_t;//B的所有字符数
				if (num_completed_t == num_unique_chars) {	
					// itÕs a match if t has been processed completely B的所有字符和A的所有字符;
					return true;
					//return i == t.length() - 1;
				}
			}
		}
		return false;
	}	
	
	public static void main(String[] args) {
		String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
		for (String[] pair : pairs) {
			String word1 = pair[0];
			String word2 = pair[1];
			boolean anagram = permutation(word1, word2);
			System.out.println(word1 + ", " + word2 + ": " + anagram);
			System.out.println(anagram(word1, word2));
		}
	}
}

补充

8中基本数据类型的默认值:

①byte short int long 这四种基本数据类型数组默认值为0

②float double 这两种数组默认值是0.0

③char这种类型数组默认值为空格

④boolean类型数组默认值为false

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值