LeetCode-07-Reverse string

Write a function whose role is to reverse the input string. The input string is given in the form of a character array char[]. Don't allocate extra space for another array, you must modify the input array in place and use O(1) extra space to solve this problem. You can assume that all characters in the array are printable characters in the ASCII code table.

Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n"," a","H"]

  1. Recursive call
  • Time complexity: O(N).
  • Space complexity: O(N)
import java.util.Scanner;

//反转字符串
public class day {
    
    
	public static void main(String[] args) {
    
    
		char [] str= {
    
    'a','b','c','d','e','f'};
		reverseString(str);
		System.out.println(str);		
	}
	  public void helper(char[] s, int left, int right) {
    
    
		    if (left >= right) return;
		    char tmp = s[left];
		    s[left++] = s[right];
		    s[right--] = tmp;
		    helper(s, left, right);
		  }
		  public static void reverseString(char[] s) {
    
    
		    helper(s, 0, s.length - 1);
		  }
		
	}
}

  1. Double pointer method
  • Time complexity: O(N).
  • Space complexity: O(1)
import java.util.Scanner;
//反转字符串
public class day {
    
    
	public static void main(String[] args) {
    
    
		char [] str= {
    
    'a','b','c','d','e','f'};
		reverseString(str);
		System.out.println(str);	
	}
	public static void reverseString(char[] s) {
    
    
		char temp;
		for(int i=0,j=s.length-1;i<j;i++,j--) {
    
    
			temp=s[i];
			s[i]=s[j];
			s[j]=temp;
		}
		
	}
}

Guess you like

Origin blog.csdn.net/TroyeSivanlp/article/details/108925541