/*
344.反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
*/
//方法一:双指针进行交换,可以使用异或运算符
class Solution {
public void reverseString(char[] s) {
if (s == null || s.length == 0){
return;
}
int head = 0, end = s.length - 1;
while (head < end){
s[head] ^= s[end];
s[end] ^= s[head];
s[head] ^= s[end];
head++;
end--;
}
}
}
/*
剑指 Offer 05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
*/
class Solution {
public String replaceSpace(String s) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' '){
buffer.append(s.charAt(i));
}else {
buffer.append("%20");
}
}
return buffer.toString();
}
}
//使用内部库函数试试
class Solution1 {
public String replaceSpace(String s) {
s.replaceAll(" ","%20");
return null;
}
}
/*
206.反转链表
题意:反转一个单链表。
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp;
while (cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
代码随想录leetcode刷题Day13-双指针
最新推荐文章于 2024-07-24 17:27:32 发布