Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Q1 02 Check Permutation: Added check for identical strings #202

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package Q1_02_Check_Permutation;

public class QuestionA {
public class QuestionA {
public static String sort(String s) {
char[] content = s.toCharArray();
java.util.Arrays.sort(content);
return new String(content);
}

public static boolean permutation(String s, String t) {
if (s.equals(t) || s.length() != t.length()) { // Permutations must have the same characters, but in different orders and must be same length
return false;
}
return sort(s).equals(sort(t));
}
}

public static void main(String[] args) {
String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
for (String[] pair : pairs) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
package Q1_02_Check_Permutation;

public class QuestionB {
public class QuestionB {
public static boolean permutation(String s, String t) {
if (s.length() != t.length()) return false; // Permutations must be same length

if (s.equals(t) || s.length() != t.length()) { // Permutations must have the same characters, but in different orders and must be same length
return false;
}

int[] letters = new int[128]; // Assumption: ASCII
for (int i = 0; i < s.length(); i++) {
letters[s.charAt(i)]++;
}

for (int i = 0; i < t.length(); i++) {
letters[t.charAt(i)]--;
if (letters[t.charAt(i)] < 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) {
Expand Down