[编程题] 字符串成环判断是否为回文字符串--字节跳动笔试题
作者:互联网
字符串成环判断是否为回文字符串
题目描述
输入一个字符串,将该字符串首尾成环,判断能否从中某位置切分,然后产生回文字符串,是则输出Yes,否则输出No
示例
例如1:
输入(字符串)
aab
成环后从a a 中切分,得到回文字符串:
aba
输出:Yes
Java代码
package ncompanydemos.p2_bytedance;
import java.util.Scanner;
/**
* @author jiyongjia
* @create 2020/7/4 - 15:03
* @descp: 输入一个字符串,将该字符串首尾成环,判断能否从中某位置切分,然后产生回文字符串
*
* 例如:aba 成环后从a a 中切分,得到回文字符串 aba 输出Yes,是回文字符串
*/
public class Exam02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
//调用
String res = solve(s);
System.out.println(res);
}
public static String solve(String s){
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
int length = chars.length;
StringBuilder stringBuilder = new StringBuilder();
int cur=i;
while (length>0){
stringBuilder.append(chars[cur%(chars.length)]);
cur++;
length--;
}
//调用回文判断
boolean compare = compare(stringBuilder.toString());
if (compare){
return "Yes";
}else {
continue;
}
}
//如果判断完还是没有回文的,返回No
return "No";
}
//字串回文判断
private static boolean compare(String s) {
char[] chars = s.toCharArray();
int left = 0;
int right = chars.length-1;
int flag = chars.length/2;
while (flag>0){
if(chars[left]!=chars[right]){
return false;
}else {
left++;
right--;
flag--;
}
}
return true;
}
}
测试输出
测试1
测试2
标签:String,int,chars,length,字符串,成环,回文 来源: https://www.cnblogs.com/jiyongjia/p/13235059.html