首页 > 解决方案 > 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 + " ");
                }
            }    
        }           
    }
}

标签: javastringsubstring

解决方案


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);
}

推荐阅读