您好,登錄后才能下訂單哦!
字符串回文是指一個字符串正著讀和反著讀都一樣的現(xiàn)象
public class PalindromeChecker {
public static void main(String[] args) {
String input = "racecar";
boolean isPalindrome = isPalindrome(input);
System.out.println("Is the input string a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(String input) {
if (input == null || input.length() == 0) {
return false;
}
int left = 0;
int right = input.length() - 1;
while (left < right) {
if (input.charAt(left) != input.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
public class StringReverser {
public static void main(String[] args) {
String input = "hello";
String reversed = reverse(input);
System.out.println("Reversed string: " + reversed);
}
public static String reverse(String input) {
if (input == null || input.length() == 0) {
return input;
}
char[] chars = input.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}
public class PalindromeSubstringFinder {
public static void main(String[] args) {
String input = "babad";
String longestPalindrome = findLongestPalindrome(input);
System.out.println("Longest palindrome substring: " + longestPalindrome);
}
public static String findLongestPalindrome(String input) {
if (input == null || input.length() == 0) {
return "";
}
int maxLength = 1;
int start = 0;
for (int i = 0; i < input.length(); i++) {
int len1 = expandAroundCenter(input, i, i);
int len2 = expandAroundCenter(input, i, i + 1);
int len = Math.max(len1, len2);
if (len > maxLength) {
maxLength = len;
start = i - (len - 1) / 2;
}
}
return input.substring(start, start + maxLength);
}
private static int expandAroundCenter(String input, int left, int right) {
while (left >= 0 && right < input.length() && input.charAt(left) == input.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
這些案例展示了字符串回文在Java中的基本應(yīng)用,包括檢查回文、反轉(zhuǎn)字符串和查找回文子串。你可以根據(jù)自己的需求對這些案例進(jìn)行修改和擴(kuò)展。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。