Day17 LeetCode 344 557(JAVA版)

目录

1. 反转字符串(LeetCode 344 题)

1.1题目

1.2思路

2. 反转字符串中的单词 III(LeetCode 557 题)

2.1题目

2.2思路


1. 反转字符串(LeetCode 344 题)

1.1题目

 

1.2思路

最好的方法就是循环双指针,一个指头一个指尾。然后头++尾--互相交换数据。时间复杂度为n,空间复杂度为1.

class Solution {
    public void reverseString(char[] s) {
        int i=0,j=s.length-1;
        while(i<j){
            char temp = s[i];
            s[i++] = s[j];
            s[j--] = temp;
        }
    }
}

2. 反转字符串中的单词 III(LeetCode 557 题)

2.1题目

 

2.2思路

接上题的思路,其实就是把字符串拆成了许多个单词进行反转,与上题思路相同。

设置end和front指针。front为0.

以i为指针循环字符串,如果遇到空格更新end为i-1。然后进行双指针字符串反转。接下来更新front。

最后循环完再遍历一次。

class Solution {
    public String reverseWords(String s) {
            int front = 0;
            int end = 0;
            char[] status = s.toCharArray();
            for(int i=0;i<status.length;i++){
                if (status[i]!=' '){
                    continue;
                }
                else {
                    end = i-1;
                    while (front<end){
                        char temp = status[front];
                        status[front] = status[end];
                        status[end] = temp;
                        front++;
                        end--;
                    }
                    if (i+1!=status.length){
                        front = i+1;
                    }
                }
            }
            end = status.length-1;
            while (front<end){
                char temp = status[front];
                status[front] = status[end];
                status[end] = temp;
                front++;
                end--;
            }
            return  String.valueOf(status);
        }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值