Pergunta de entrevista da empresa Carahsoft

In language of your choosing write a program with a single function to determine if 2 strings supplied by the user are anagrams. Make the program as robust as possible to accommodate imperfect user input.

Resposta da entrevista

Sigiloso

7 de fev. de 2018

import java.util.Arrays; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str1, str2; while (true) { System.out.println("Enter a string and Press Enter"); str1 = scan.nextLine(); System.out.println("Now enter another string"); str2 = scan.nextLine(); // check if user enters only letters if (str1.matches("[a-zA-Z]+") == true && str2.matches("[a-zA-Z]+") == true) { System.out.println(isAnagram(str1, str2) + "\n"); } else if (str1.length() == 0 || str2.length() == 0) { // check if user enters empty string System.out.println("You have entered an empty string. Please try again.\n"); } else { System.out.println("You have entered one or more strings that contain numbers or special characters. Please try again.\n"); } } } public static boolean isAnagram(String str1, String str2) { char[] input1, input2; input1 = str1.toCharArray(); input2 = str2.toCharArray(); Arrays.sort(input1); Arrays.sort(input2); if (input1.length != input2.length) return false; // not anagram if lengths differ for (int i = 0; i < input1.length; i++) { if (input1[i] != input2[i]) return false; // return false as soon as char differs } return true; } }