您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
字符串回文是指一个字符串正着读和反着读都一样的现象
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。