题目描述
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
"This is nowcoder","is This nowcoder"
返回:true
"Here you are","Are you here"
返回:false
利用位运算,当该位字符出现的时候,该位的数字加上1,第二个字符串该位字符出现的时候,减去1,如果某一个位为负数,则直接返回false
import java.util.*; public class Same { public boolean checkSam(String stringA, String stringB) { // write code here if((stringA==null||stringA.length()==0)&&(stringB==null||stringB.length()==0)){ return true; } int[] up = new int[256]; for(int i=0;i<256;i++){ up[i]=0; } for(int i=0;i<stringA.length();i++){ char ch = stringA.charAt(i); up[ch-'0']++; } for(int j=0;j<stringB.length();j++){ char ch = stringB.charAt(j); up[ch-'0']--; if(up[ch-'0']<0){ return false; } } for(int i=0;i<256;i++){ if(up[i]<0){ return false; } } return true; } }