1. Reverse a string

1. Reverse a string


Problem link :- click here


package programs;

public class String__1
{

	static String reverseString(String s)
	{
		//1st method
		/*
        		StringBuffer str = new StringBuffer(s);
        		str.reverse();
        		System.out.println("Reversed string is : " + str);
		*/
		/*
		     2nd method
		     in this we will copy the string to a char array and then reverse that array 
		    and that array.
		*/
		char string[] = s.toCharArray();
		int i, j;
		i = 0;
		j = string.length - 1;
		
		while(i<j)
		{
			char temp = string[i];
			string[i] = string[j];
			string[j] = temp;
			i++;
			j--;
		}
		
		String st = string.toString();
		return st;
	}
	
	public static void main(String[] args)
	{
		String s = "hello";
		System.out.println("Given string is : " + s);
		
		s = reverseString(s);
		System.out.println("String after reversing : " + s);
	}
}

Time complexity :- O(n)
Space complexity :- O(1)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree