Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;
}
share|improve this question
    
I have rolled back the edits that changed the code. Please see what you may and may not do after receiving answers. –  mjolka Jan 19 at 0:46
    
I see. I didn't know about that, my apologies! –  poppoppushpop Jan 19 at 0:48

1 Answer 1

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

share|improve this answer
    
ohhhh you're right! i'm working on it now, will update soon! –  poppoppushpop Jan 18 at 23:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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