Day04HomeWork

package day04.homework;

import java.util.Scanner;

/**
* 检查英文单词
* 请编写一个程序,接收用户在控制台输入的两个英文单词
* 判断其中一个单词的所有字符重新排列后,能否变为另一个单词
*
*/
public class Test01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
String s2 = scanner.next();
//先判断两个英文单词的长度是否相同
if (s1.length()!=s2.length()){
System.out.println(false);
}else {
isWord(s1,s2);
}
}

/**
* 定义一个方法,用来判断两个单词中字母出现的次数是否一样
* @param s1 第一个单词
* @param s2 第二个单词
*/
public static void isWord(String s1,String s2) {
//定义字符数组用来存储字符串数据
char[] charArrays1 = s1.toCharArray();
char[] charArrays2 = s2.toCharArray();
int c1[] = new int[256];
for (int i = 0; i < charArrays1.length; i++) {
int c2 = charArrays1[i];
c1[c2]++;
}
boolean flag = true;
for (int i = 0; i < charArrays2.length; i++) {
if (c1[(int)charArrays2[i]]<=0){
flag = false;
break;
}else {
c1[(int)charArrays2[i]]--;
}
}
if (flag){
System.out.println(true);
}else {
System.out.println(false);
}
}
}

package day04.homework;

/**
* 计算数组中元素的距离
* 给定一个字符串数组strs,再给定2个字符串str1和str2
* 返回在strs中str1与str2的最小距离。
* 如果str1或str2为null,或不在strs中,返回-1
*/
public class Test02 {
public static void main(String[] args) {
String[] strs ={"abc","cde","bcd","ac","bcd","ac"};
String str1 = "abc";
String str2 = "ac";
int index1 = -1;
int index2 = -1;
int min = strs.length;
if (str1==null||str2==null){
min = -1;
System.out.println(min);
}else if (str1.equals(str2)){
min = 0;
System.out.println(min);
}else {
for (int i = 0; i < strs.length ; i++) {
if (strs[i].equals(str1)){
min=Math.min(min,index2==-1?min:i-index2);
index1 =i;
}
if (strs[i].equals(str2)){
min=Math.min(min,index1==-1?min:i-index1);
index2=i;
}
}
if (min == strs.length){
System.out.println(-1);
}else {
System.out.println(min);
}
}
}
}