Second brush LeetCode344. 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 to 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.

Because it must be modified in place, we can use the double pointer method

Solution 1: Double pointer

Writing one:

public void reversString(char[] s) {
    
    
	for (int i = 0; i < s.length / 2; i++) {
    
    
		char temp = s[i];
		int a = s.length - 1 - i;
		s[i] = s[a];
		s[a] = temp;
	}
}

Writing method two:

public void reverseString3(char[] s) {
    
    
	int left = 0;
	int right = s.length - 1;
	while (left < right) {
    
    
		char a = s[left];
		s[left++] = s[right];
		s[right--] = a;
	}
}

Solution 2: Rely on the reverse method of StringBuilder

// StringBuilder做法
public void reverseString(char[] s) {
    
    
	String str = new String(s);
	StringBuilder sBuilder = new StringBuilder(str);
	str = sBuilder.reverse().toString();
	for (int i = 0; i < str.length(); i++) {
    
    
		s[i] = str.charAt(i);
	}
}

end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108121119