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;

1 Answer 1


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

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.