Reverse a string in Java

前端 未结 30 2604
礼貌的吻别
礼貌的吻别 2020-11-21 13:12

I have \"Hello World\" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there

30条回答
  •  孤独总比滥情好
    2020-11-21 13:52

    Just For Fun..:)

    Algorithm (str,len):
      char reversedStr[] =new reversedStr[len]
      Traverse i from 0 to len/2 and then
        reversedStr[i]=str[len-1-i]  
        reversedStr[len-1=i]=str[i]
      return reversedStr;
    

    Time Complexity:O(n) Space Complexity :O(n)

     public class Reverse {
        static char reversedStr[];    
        public static void main(String[] args) {
            System.out.println(reversestr("jatin"));
        }        
        private static String reversestr(String str) {
            int strlen = str.length();
            reversedStr = new char[strlen];
            
            for (int i = 0; i <= strlen / 2; i++) {
                reversedStr[i] = str.charAt(strlen - 1 - i);
                reversedStr[strlen - 1 - i] = str.charAt(i);
    
            }
            return new String(reversedStr);
        }
    
    }
    

提交回复
热议问题