代码随想录Day9
lc151
package 字符串;
import java.util.Scanner;
public class lc151 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s = sc.nextLine();
System.out.println(fuction01(s));
}
private static StringBuilder fuction01(String s) {
// System.out.println("ReverseWords.removeSpace() called with: s = [" + s + "]");
int start = 0;
int end = s.length() - 1;
while (s.charAt(start) == ' ') start++;
while (s.charAt(end) == ' ') end--;
StringBuilder sb = new StringBuilder();
while (start <= end) {
char c = s.charAt(start);
if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') {
sb.append(c);
}
start++;
}
// System.out.println("ReverseWords.removeSpace returned: sb = [" + sb + "]");
return sb;
}
}
kam55
package 字符串;
import java.util.Scanner;
public class kam55 {
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--;
}
}
/* public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String str = sc.nextLine();
System.out.println(functon(n,str));
}
//事件超时
private static String functon(int n, String str) {
StringBuilder sb=new StringBuilder();
sb.append(str.substring(str.length()-n));
sb.append(str.substring(0,str.length()-n));
String s = sb.toString();
String resl = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)==32){ //空格的码表是32
continue;
}
resl+=s.charAt(i);
}
return resl;
}*/
}
KMP求next()
private static int[] getNext(String s) {
int next[]=new int[s.length()];
next[0]=0;
int j=0;
for (int i = 1; i < s.length(); i++) {
while (j>0 && s.charAt(j)!=s.charAt(i)){
j=next[j-1];
}
if (s.charAt(j)==s.charAt(i)){
j++;
}
next[i]=j;
}
return next;
}
lc28
class Solution {
//前缀表(不减一)Java实现
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle.charAt(j) != haystack.charAt(i))
j = next[j - 1];
if (needle.charAt(j) == haystack.charAt(i))
j++;
if (j == needle.length())
return i - needle.length() + 1;
}
return -1;
}
private void getNext(int[] next, String s) {
int j = 0;
next[0] = 0;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(j) != s.charAt(i))
j = next[j - 1];
if (s.charAt(j) == s.charAt(i))
j++;
next[i] = j;
}
}
}
SHEIN希音公司福利 222人发布
