java - Pallindrome 字符串替换为 * 字符
问题描述
输入一个包含一些回文子串的字符串。找出回文子串的位置(如果存在)并将其替换为 *。(例如,如果输入字符串是“<code>bob has a radar plane”,那么它应该转换为“<code>** has a ***** plane”。
我的代码如下。
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
解决方案
split() 将丢失源字符串中的双空格和标点符号,并在内存中产生大量无用的对象。这是更正确的解决方案。恕我直言
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}
推荐阅读
- python - 如何生成扁平列表的所有排列?
- node.js - ExpressJS/Passport-SAML Single Log Out 直接重新登录
- javascript - 在使用 JavaScript 提交时将类添加到输入
- django - Heroku 超时
- php - 使用php从字符串中提取值
- android - 匕首2的问题
- java - 从资源文件夹中读取文件总是在 Spring Boot 应用程序中给出 Inputstream 为空
- uwp - [UWP][InkCanvas] 如何在 Touch 中使用 InkCanvas 绘制路径
- deep-learning - 标量类型 Short 的预期对象,但在调用 _th_mm 时获得了参数 #2 'mat2' 的标量类型 Float
- validation - 在 Kotlin 中,根据属性的类型限制注解目标