user3529942
user3529942

Reputation: 23

Comparing the reverse word of a string to the original string Java

This is the solution I came up with:

public void reverse(String str1, String str2){
int j = str2.length() - 1; 

if(str1.length() != str2.length()) 
{ 
    return false; 
} 
else 
{ 
    for(int i = 0; i < str1.length(); i++) 
    { 
       if((str1.charAt(i) == str2.charAt(j)) && j >=0) 
       {     
          j--; 
       } 
       else 
       { 
          return false; 
       } 
    } 
} 
  return true; 
}

There were other solutions I saw such as 1. Uses toCharArray() and Arrays.sort(content) 2. Algorithm that counts how many times the character appears using two arrays (one for each string) <-- I was thinking this solution is inaccurate because the reversed string could have the same amount of characters as the original string but is not the reverse of the original string. i.e. word =/= dorw

Which of these solution has the best O-notation? And what does Arrays.sort(content) do?

Upvotes: 0

Views: 3056

Answers (5)

weston
weston

Reputation: 54781

It sounds like a test for palindrome, which is "is the reverse the same as the original?". For that you do not need to reverse the string, so you only have one argument:

public static boolean isPalindrome(String str)
{
  int len = str.length();
  int max = len/2;
  for(int i=0; i < max; i++)
    if(str.charAt(i) != str.charAt(len - i - 1))
      return false;
  return true;
}

The key bit to note is you do not need to compare anymore than half of the string (rounded down).

Upvotes: 0

Theo
Theo

Reputation: 21

You didn't need to use a sorting algorithm. Your first solution has a O(n) complexity and the sorting algorithm implemented in Arrays.sort() has o(nlog(n)).

Upvotes: 0

carboncomputed
carboncomputed

Reputation: 1620

The best way to do this is in O(n). It seems like you did that. Walk through the beginning while walking through the end comparing characters, if theyre not equal, return false. If it makes it to the end of the string return true.

//Assuming you checked the length
for(int i = 0; i< str1.length();i++){
   if(str1[i] != str2[str2.length-i-1]
       return false;
} 
return true;

I didnt test it but it should work.

Upvotes: 0

Jens
Jens

Reputation: 69440

I think the best solution is to reverse the str2 and use the euals method of string to compare both strings:

public boolean reverse(String str1, String str2){
   return str1.equals(new StringBuilder(str2).reverse().toString())
}

Upvotes: 3

mowol
mowol

Reputation: 11

If your method is void, it doesn't make much sense to return false or true. Your method should probably be public boolean reverse(..).

For the code, i think this is faster (if i understand your question).

String reverse = new StringBuffer(str2).reverse().toString();
return reverse.equals(str1);

Upvotes: 0

Related Questions