day9第四章 字符串part02| 151.翻转字符串里的单词 |卡码网:55.右旋转字符串|28. 实现 strStr() |459.重复的子字符串

151.翻转字符串里的单词

class Solution {
    public String reverseWords(String s) {
        //// 删除首尾空格,分割字符串
        String[] str = s.trim().split(" ");
        StringBuilder sb = new StringBuilder();
        //// 倒序遍历单词列表
        for(int i = str.length - 1; i >= 0; i--){
            //遇到空单词则跳过
            if(str[i].equals("")) continue;
            //将单词拼接至 StringBuilder
            sb.append(str[i] + " ");
        }
        // 转化为字符串,删除尾部空格,并返回
        return sb.toString().trim();
    }
}

 

卡码网:55.右旋转字符串

import java.util.Scanner;
//把字符串整体反转,然后按照分割位置再反转一次。
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        String s = in.nextLine();
        
        int len = s.length();
        char[] chars = s.toCharArray();
        reverseString(chars, 0, n - len - 1);
        reverseString(chars, 0, n - 1);
        reverseString(chars, n - 1, len -1);
        
        System.out.println(chars);
    }
    
    public static void reverseString(char[] ch, int start, int end){
        while(start < end){
            ch[start] ^= ch[end];
            ch[end] ^= ch[start];
            ch[start] ^= ch[end];
            start++;
            end--;
        }
    }
}

 

 

28. 实现 strStr()

没看明白,参考了:

https://www.bilibili.com/video/BV1jb411V78H/?spm_id_from=333.788.recommend_more_video.9&vd_source=93305b078442e910f24518b5f087d908

459.重复的子字符串 

 

字符串总结  双指针回顾

posted @ 2024-08-26 08:30  爱刷题的小盒子  阅读(240)  评论(0编辑  收藏  举报