4
\$\begingroup\$

I'm trying to solve simple Java problems in various ways. Could anyone comment about the code, like how it could be better, and what could be a problem?

// When using already-defined-method is allowed
static String reverseStringByChar1(String str) {
 return str == null ? null : new StringBuilder(str).reverse().toString();
}
// When using already-defined-method is not allowed
static String reverseStringByChar2(String str) {
 if (str == null)
 return null;
 int length = str.length();
 char[] charArray = new char[length];
 for (int i = length-1, j = 0; i >= 0; i--, j++)
 charArray[i] = str.charAt(j);
 return new String(charArray);
}
// When using extra data structure is not allowed 
// (Is there any way not to use extra memory? Here like the temp.)
static String reverseCharacterArray(char[] chars) {
 if(chars.length == 0)
 return null;
 for (int i = 0, j = chars.length-1; i < chars.length / 2; i++, j--) {
 /* char temp = chars[i];
 chars[i] = chars[j];
 chars[j] = temp;
 */
 char temp = chars[i];
 chars[i] = chars[chars.length-1-i];
 chars[chars.length-1-i] = temp;
 }
 return new String(chars);
}
// When comparing two strings to see if they are permutations of each other.
static boolean arePermutations(String str1, String str2) {
 // can be trimmed
 // need to know what to do with uppercases and lowercase
 if (str1 == null || str2 == null || str1.length() != str2.length())
 return false;
 // assuming askii code
 boolean[] str1Array = new boolean[128];
 for (char c : str1.toCharArray())
 str1Array[c] = true;
 for (char c : str2.toCharArray()) {
 if (!str1Array[c])
 return false;
 }
 return true;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 18, 2015 at 22:57
\$\endgroup\$
2
  • \$\begingroup\$ I have rolled back the edits that changed the code. Please see what you may and may not do after receiving answers . \$\endgroup\$ Commented Jan 19, 2015 at 0:46
  • \$\begingroup\$ I see. I didn't know about that, my apologies! \$\endgroup\$ Commented Jan 19, 2015 at 0:48

1 Answer 1

2
\$\begingroup\$

There's a problem with the algorithm for arePermutuations. For instance, arePermutations("aab", "bba") will return true.

answered Jan 18, 2015 at 23:07
\$\endgroup\$
1
  • \$\begingroup\$ ohhhh you're right! i'm working on it now, will update soon! \$\endgroup\$ Commented Jan 18, 2015 at 23:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.