求职面试题(两个字符串是否包含相同的字符)


求职面试题(两个字符串是否包含相同的字符)



本篇博客包括针对题目包括两个比较字符串是否包括相同字符的方法:

(1)把字符串转化为数组,然后对数组排序,最后比较两字符串是否相等。


(2)以空间代替时间。

package com.robin.stringAndSZ;

import java.util.Arrays;

public class CompareString {

	public static void compare1(String str1,String str2){
		char[] str1ToChar = str1.toCharArray();
		char[] str2ToChar = str2.toCharArray();
		
		Arrays.sort(str1ToChar);
		Arrays.sort(str2ToChar);
		
		if(new String(str1ToChar).equals(new String(str2ToChar))){
			System.out.println("the two string is composed of the same char");
		}else{
			System.out.println("the two string isn't composed of the same char");
		}
	}
	
	public static void compare2(String str1,String str2){

		char[] str1ToChar = str1.toCharArray();
		char[] str2ToChar = str2.toCharArray();
		char[] str = new char[256];
		for(int i = 0; i < str.length; i++){
			str[i] = 0;
		}
		
		for(int i = 0 ; i < str1ToChar.length ; i++){
			str[str1ToChar[i]-'0']++;
		}
		
		for(int i = 0 ; i < str2ToChar.length ; i++){
			str[str2ToChar[i]-'0']--;
		}
		
		for(int i = 0; i < str.length; i++){
			if(str[i] != 0){
				System.out.println("the two string isn't composed of the same char");
				return;
			}
		}
		
		System.out.println("the two string is composed of the same char");
	}
	
	public static void main(String[] args) {
		
		String str1 = "aaaabbbb";
		String str2 = "abababab";
		String str3 = "abcabcab";
		
		compare1(str1,str3);
		compare1(str1,str2);
		
		compare2(str1,str3);
		compare2(str1,str2);
	}

}

你可能感兴趣的:(java,字符串,面试题,相同字符)