简体   繁体   中英

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. ie word =/= dorw

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

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())
}

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);

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.

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)).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM