算法Day7 | Leetcode344.反转字符串、541. 反转字符串II、替换数字(acm模式)

344.反转字符串

力扣链接
在这里插入图片描述

思路

双指针

代码

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

541. 反转字符串II

力扣链接
在这里插入图片描述

思路

暴力求解写崩溃了^^最关键的点还是在于右边界是通过长度和目前所在位置走k个看谁要更小来界定。

代码

暴力

class Solution {
    public String reverseStr(String s, int k) {
        String result="";
        int sumTwo=s.length()/(2*k);
        int countTwo=0;
        while(countTwo<sumTwo){
            String stringSub=s.substring(countTwo*2*k,countTwo*2*k+k+1);
            char[] charSub=new char[stringSub.length()];
            for(int i=0;i<stringSub.length();i++){
                charSub[i]=stringSub.charAt(i);
            }
            int left=0;
            int right=sub.length-1;
            while(left<right){
                char temp=charSub[left];
                charSub[left++]=charSub[right];
                charSub[right--]=temp;
            }
            countTwo++;
        }

        int sumOne=(s.length()-sumTwo*2*k)/k;

    }
}

数组

class Solution {
    public String reverseStr(String s, int k) {
        char[] reverse=s.toCharArray();
        for(int i=0;i<s.length();i+=2*k){
            int left=i;
            int right=Math.min(s.length()-1,i+k-1);
            while(left<right){
                char temp=reverse[left];
                reverse[left++]=reverse[right];
                reverse[right--]=temp;
            }
        }
        return new String(reverse);
    }
}

替换数字(acm模式)

力扣链接
在这里插入图片描述

思路

拼接字符串,注意判断那个0和9要加单引号。但是我看到别的解法是通过Character.isDigit()来判断数字个数然后创建相应大的数组

代码

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        String s=in.nextLine();
        String result=changeString(s);
        System.out.println(result);
    } 
    
    public static String changeString(String s){
        String result="";
        for(int i=0;i<s.length();i++){
            if(s.charAt(i) >= '0' && s.charAt(i) <= '9'){
                result+="number";
            }else{
                result+=s.charAt(i);
            }
        }
    return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值