-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation1.java
More file actions
40 lines (27 loc) · 1.06 KB
/
Permutation1.java
File metadata and controls
40 lines (27 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.java.cci.practice;
import java.util.Arrays;
public class Permutation1 {
public static boolean permutation(String s, String t) {
if (s.length() != t.length()) return false; // Permutations must be same length
int[] letter = new int[128];
for (int i = 0; i < s.length(); i++) {
letter[s.charAt(i)]++;
}
for (int j=0 ; j <t.length();j++){
letter[t.charAt(j)] --;
if (letter[t.charAt(j)] < 0) {
return false;
}
}
return true; // letters array has no negative values, and therefore no positive values either
}
public static void main(String[] args) {
String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
for (String[] pair : pairs) {
String word1 = pair[0];
String word2 = pair[1];
boolean anagram = permutation(word1, word2);
System.out.println(word1 + ", " + word2 + ": " + anagram);
}
}
}