如何用Java实现无数组从回文中提取指定长度的子回文
解决方案:提取句子中的回文及指定长度的子回文
前提说明
假设你已实现的单个单词回文判断方法如下(如果你的实现不同,只需保证isPalindrome方法能正确返回布尔值即可):
public static boolean isPalindrome(String word) { int left = 0; int right = word.length() - 1; while (left < right) { if (word.charAt(left) != word.charAt(right)) { return false; } left++; right--; } return true; }
1. 从输入句子中提取所有回文单词
以下方法不使用数组,通过indexOf和substring逐个截取句子中的单词,结合回文判断方法筛选出所有回文单词:
public static String extractPalindromesFromSentence(String sentence) { if (sentence == null || sentence.trim().isEmpty()) { return ""; } StringBuilder palindromeBuilder = new StringBuilder(); int wordStart = 0; int spacePos = sentence.indexOf(' '); // 遍历截取每个单词 while (spacePos != -1) { String currentWord = sentence.substring(wordStart, spacePos).trim(); if (!currentWord.isEmpty() && isPalindrome(currentWord)) { if (palindromeBuilder.length() > 0) { palindromeBuilder.append(" "); } palindromeBuilder.append(currentWord); } wordStart = spacePos + 1; spacePos = sentence.indexOf(' ', wordStart); } // 处理句子最后一个单词 String lastWord = sentence.substring(wordStart).trim(); if (!lastWord.isEmpty() && isPalindrome(lastWord)) { if (palindromeBuilder.length() > 0) { palindromeBuilder.append(" "); } palindromeBuilder.append(lastWord); } return palindromeBuilder.toString(); }
2. 从回文单词中提取指定长度的子回文
该方法基于回文的中心对称性,直接从原回文的中心向两侧截取目标长度的子串,全程不使用数组:
public static String extractSubPalindrome(String palindromeWord, int targetLength) { // 参数合法性校验 if (palindromeWord == null || !isPalindrome(palindromeWord)) { throw new IllegalArgumentException("输入必须是有效的回文字符串"); } int wordLength = palindromeWord.length(); if (targetLength <= 0 || targetLength > wordLength || (targetLength % 2) != (wordLength % 2)) { throw new IllegalArgumentException("指定长度不合法:需为正整数、不超过原单词长度,且与原单词长度奇偶性一致"); } // 计算截取的起始和结束索引 int centerIndex = wordLength / 2; int offset = targetLength / 2; int start = centerIndex - offset; int end = centerIndex + offset + 1; // substring为左闭右开区间 return palindromeWord.substring(start, end); }
测试示例
调用extractSubPalindrome("racecar", 3)将返回"cec",符合需求。
内容的提问来源于stack exchange,提问作者Joe Tiwari
相关产品推荐
相关产品推荐

