統計迴文
題目詳述:統計迴文
解題思路:通過字符串切割將s1插入到s中,利用StringBuffer裏的reverse方法將插入後的字符串反轉,通過比較反轉前和反轉後字符串內容是否一致判斷是否爲迴文串。
import java.util.Scanner;
public class Main {
private static int test(String s,String s1){
int count = 0;
for(int i = 0; i<=s.length(); i++){
String reBefor = s.substring(0,i)+s1+s.substring(i,s.length()); //反轉前
String reAefor = new StringBuilder(reBefor).reverse().toString(); //反轉後
if(reBefor.equals(reAefor)){
count = count+1;
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String s = sc.next();
String s1 = sc.next();
System.out.println(test(s, s1));
}
}
}
字符串中找出連續最長的數字串
題目詳述:字符串中找出連續最長的數字串
解題思路:用max表示經過的數字長度最大值,count表示數字計數器,當爲字母時重置爲0;end表示數字尾部,每次滿足數字時,對max進行判斷,當max小於於count時,更新max和end
class Main{
//abcd12345ed125ss123456789
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str = scanner.nextLine();
int max = 0,count=0,end=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)>='0' && str.charAt(i)<='9'){
count++; //計數
if(max<count){
max= count;//更新數字最大長度max
end = i;//更新數字尾部下標end
}
}else{
count = 0; //遇到字母 置爲0
}
}
System.out.println(str.substring(end-max+1,end+1)); //[)
}
}
}