代码随想录leetcode刷题Day13-双指针

/*
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; }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值