《蘑菇街编程题》回文串
来源:互联网 发布:linux不保存退出 编辑:程序博客网 时间:2024/04/30 18:01
题目:给定一个字符串,问是否能通过添加一个字母将其变为回文串。
输入描述:
一行一个由小写字母构成的字符串,字符串长度小于等于10。
输出描述:
输出答案(YES\NO).
输入例子1:
coco
输出例子1:
YES
解析:思路是求得最大的回文子串,然后看最大的回文子串是否等于字符串的长度减1,如果等于,返回YES,否则返回NO
import java.util.Scanner;/** * Created by HP on 2017/8/4. */public class Main { //ceabadd //abba public static String maxPalinedrom(String s){ int max=0; int left=0,right=0; for(int i=0;i<s.length();i++){//最大回文是奇数的情况 int leftIndex=i-1; int rightIndex=i+1; while (leftIndex>=0&&rightIndex<s.length()){ if(s.charAt(leftIndex)==s.charAt(rightIndex)){ leftIndex--; rightIndex++; }else { break; } } leftIndex++; rightIndex--; if((rightIndex-leftIndex+1)>=max){ max=rightIndex-leftIndex+1; left=leftIndex; right=rightIndex; } } for(int i=0;i<s.length();i++){//最大回文是偶数的情况//abba int leftIndex=i; int rightIndex=i+1; while (leftIndex>=0&&rightIndex<s.length()){ if(s.charAt(leftIndex)==s.charAt(rightIndex)){ leftIndex--; rightIndex++; }else { break; } } leftIndex++; rightIndex--; if((rightIndex-leftIndex+1)>=max){ max=rightIndex-leftIndex+1; left=leftIndex; right=rightIndex; } } if(max==s.length()-1){ return "YES"; } //return s.substring(left,right+1);//题目并不要求输出最大回文子串,但是可以求得的最大连续子回文子串 return "NO"; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ System.out.println(maxPalinedrom(sc.next())); } }}
阅读全文
0 0
- 《蘑菇街编程题》回文串
- 回文串---蘑菇街2016研发工程师在线编程题
- 蘑菇街2016研发工程师编程题--回文串
- 蘑菇街 回文串
- [蘑菇街]回文串
- 笔试题(蘑菇街):回文串
- [编程题] 回文串 java 蘑菇街2016研发工程师在线编程题
- 牛客网---2016---蘑菇街回文串
- 蘑菇街2016研发工程师_回文串
- 蘑菇街2016校园招聘——回文串
- 蘑菇街2016招聘笔试(回文串)
- 2016蘑菇街编程题5题
- 2017蘑菇街编程题详解
- 蘑菇街2016研发工程师在线编程题
- 蘑菇街2016暑期实习笔试编程题
- 2016.3.31 蘑菇街笔试编程题2
- 投篮游戏---蘑菇街2016研发工程师在线编程题
- 聊天------蘑菇街2016研发工程师在线编程题
- MySQL数据类型char与varchar中数字代表的究竟是字节数还是字符数?
- Java 集合系列07之 Stack详细介绍(源码解析)和使用示例
- D
- android 6.0权限全面详细分析和解决方案
- 13.6—动态规划—Interleaving String
- 《蘑菇街编程题》回文串
- 利用crf++来训练一个中文分词模型
- 13.8—动态规划—Minimum Path Sum
- frp 内网穿透
- 大学如何组织管理外包团队进行研发?
- Java--Proxy代理介绍及实现机制
- 13.9—动态规划—Edit Distance
- Spring XML解析过程
- KindEditor得不到textarea值的解决方法