【題目】
給定兩個字符串str1和str2,如果str1和str2中出現的字符種類一樣且每種字符出現的次數也一樣,那么str1和str2互為變形詞。請實現函數判斷兩個字符串是否互為變形詞。
【舉例】
str1="123",str2="231",返回true。
str1="123",str2="2331",返回false。
import java.util.Scanner;public class ChangeWord { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.PRintln("請輸入字符串:"); String str1 = sc.nextLine(); String str2 = sc.nextLine(); if(isChange(str1,str2)){ System.out.println("true"); }else{ System.out.println("false"); } } public static boolean isChange(String s1, String s2){ if(s1 == null || s2 == null || s1.length() != s2.length() ){ return false; } char[] chas1 = s1.toCharArray(); char[] chas2 = s2.toCharArray(); int[] map = new int[256]; for(int i = 0;i<chas1.length;i++){ map[chas1[i]]++; } for(int i=0;i<chas2.length;i++){ if(map[chas2[i]]-- == 0){ return false; } } return true; }}
新聞熱點
疑難解答