您好,登錄后才能下訂單哦!
字符串回文是指一個字符串正著讀和反著讀都一樣的現象
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中的基本應用,包括檢查回文、反轉字符串和查找回文子串。你可以根據自己的需求對這些案例進行修改和擴展。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。