Skip to content

Commit 9c9446a

Browse files
committed
Refactor based on all standard rules
./run.sh pmd -d /home/anit/work/codechallenge-java-pom/src/main/java/hackerrank/java/Anagrams.java -f text -R /home/anit/work/codechallenge-java-pom/.pmd --cache /tmp/codechallenge-pmd-analysis | less Remaining issue /home/anit/work/codechallenge-java-pom/src/main/java/hackerrank/java/Anagrams.java:71: LawOfDemeter: Potential violation of Law of Demeter (method chain calls)
1 parent 92b375f commit 9c9446a

File tree

1 file changed

+64
-19
lines changed

1 file changed

+64
-19
lines changed

src/main/java/hackerrank/java/Anagrams.java

Lines changed: 64 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,80 @@
33
import java.util.Arrays;
44
import java.util.Locale;
55

6+
/**
7+
* Check if two strings are anagram (case insensitive)
8+
*
9+
*/
610
public class Anagrams {
7-
String first;
8-
String second;
911

10-
public Anagrams(String first, String second) {
12+
/**
13+
* First String
14+
*/
15+
private final String first;
16+
17+
/**
18+
* Second String
19+
*/
20+
private final String second;
21+
22+
/**
23+
* Instantiate first and second strings.
24+
*
25+
* @param first String
26+
* @param second String
27+
*/
28+
public Anagrams(final String first, final String second) {
1129
this.first = first;
1230
this.second = second;
1331
}
1432

33+
public String getFirst() {
34+
return first;
35+
}
36+
37+
public String getSecond() {
38+
return second;
39+
}
40+
41+
/**
42+
* Return true if two strings are anagram.
43+
*
44+
* @return Boolean
45+
*/
1546
public boolean isAnagram() {
47+
int count = 0;
48+
final int firstLen = first.length();
1649

17-
if ( first.length() != second.length() ) {
18-
return false;
19-
}
20-
Locale locale = Locale.ENGLISH;
21-
String firstUpper = first.toUpperCase(locale);
22-
String secondUpper = second.toUpperCase(locale);
23-
char[] firstCharArr = firstUpper.toCharArray();
24-
char[] secondCharArr = secondUpper.toCharArray();
25-
Arrays.sort(firstCharArr);
26-
Arrays.sort(secondCharArr);
27-
28-
for (int i=0; i < first.length(); i++) {
29-
30-
if ( firstCharArr[i] != secondCharArr[i] ) {
31-
return false;
50+
if ( equal(firstLen, second.length()) ) {
51+
52+
final char[] firstCharArr = sort(first);
53+
final char[] secondCharArr = sort(second);
54+
55+
while (count < firstLen) {
56+
57+
if ( !equal(firstCharArr[count],
58+
secondCharArr[count]) ) {
59+
break;
60+
}
61+
count++;
3262
}
3363
}
3464

35-
return true;
65+
return count == firstLen;
66+
}
67+
68+
private char[] sort(final String randomStr) {
69+
final Locale locale = Locale.ENGLISH;
70+
71+
final char[] upperChar = randomStr.toUpperCase(locale)
72+
.toCharArray();
73+
Arrays.sort(upperChar);
74+
75+
return upperChar;
76+
}
77+
78+
private boolean equal(final int first,
79+
final int second) {
80+
return first == second;
3681
}
3782
}

0 commit comments

Comments
 (0)