算法day08 | Java | 字符串 | LeetCode 151,卡码55,28,459

139 阅读1分钟

java

输出

//  char[] chars = s.toCharArray();
System.out.println(chars);

string转int

int i = Integer.parseInt(xx)

151.翻转字符串里的单词

整体思路:整体字符串反转,每个单词反转,删除空格(carl的思路)

这里java的思路是先去掉多余的空格

class Solution {
    public String reverseWords(String s) {
        char[] rawStr = s.toCharArray();
        char[] newStr = new char[rawStr.length+1]; //这里为什么要加1,因为在18行的时候会多一个空格
        
        int i = rawStr.length-1;
        int newPos = 0;
        while(i>=0) {
            //去掉空格-单词的右边界
            while(i>=0 && rawStr[i]==' ') {i--;}
            int end = i;
            //单词的左边界
            while(i>=0 && rawStr[i]!=' ') {i--;}

            for(int j=i+1; j<=end; j++) {
                newStr[newPos++] = rawStr[j];
                if(j==end) {
                    newStr[newPos++] =' ';
                }
            }
        }

        if(newPos == 0) {
            return "";
        } else {
            return new String(newStr,0,newPos-1);
        }
    }
}

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

Java不能在字符串上修改,所以使用java一定要开辟新空间

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, len - 1);  //反转整个字符串
        reverseString(chars, 0, n - 1);  //反转前一段字符串,此时的字符串首尾尾是0,n - 1
        reverseString(chars, n, len - 1);  //反转后一段字符串,此时的字符串首尾尾是n,len - 1
        
        System.out.println(chars);

    }

    public static void reverseString(char[] ch, int start, int end) {
        //异或法反转字符串,参照题目 344.反转字符串的解释
        while (start < end) {
            ch[start] ^= ch[end];
            ch[end] ^= ch[start];
            ch[start] ^= ch[end];
            start++;
            end--;
        }
    }
}

KMP

28. 实现 strStr()

459.重复的子字符串