Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class PO2_Compare_Character_Arrays_Lexicographically {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- char[] arr1 = scanner.nextLine().toCharArray();
- char[] arr2 = scanner.nextLine().toCharArray();
- boolean arrayEqual = true;
- // In lexicographic order the elements are compared one by one starting from the very left.
- // If the elements are not the same, the array, whose element is smaller (comes earlier in the alphabet),
- // comes first.
- // If the elements are equal, the next character is compared.
- // If the end of one of the arrays is reached, without finding different elements, the shorter array is the smaller
- // (comes earlier lexicographically).
- // If all elements are equal, the arrays are equal
- if (arr1.length > arr2.length) {
- System.out.println("Second array is lexicographically smaller.");
- } else if (arr1.length < arr2.length) {
- System.out.println("First array is lexicographically smaller.");
- } else {
- for (int i = 0; i < arr1.length; i++)
- {
- if (arr1[i] < arr2[i])
- {
- System.out.println("First array is lexicographically smaller.");
- arrayEqual = false;
- break;
- }
- if (arr1[i] > arr2[i])
- {
- System.out.println("Second array is lexicographically smaller.");
- arrayEqual = false;
- break;
- }
- }
- if (arrayEqual) {
- System.out.println("Arrays are lexicographically equal.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment