本文转载自点击打开链接
既然通过添加一个字母可以变为回文串,那么通过删除与添加的字母相对位置的字符,应该亦为回文串。
例如:
‘abcb’在末尾添加’a’ —> ‘abcba’为回文串
‘abcb’删除与想要添加的字符’a’对应位置的字符 —> ‘bcb’亦为回文串
‘aabbaab’在头部添加’b’ —> ‘baabbaab’为回文串
‘aabbaab’删除与想要添加的字符’b’对应位置的字符 —> ‘aabbaa’亦为回文串
Java算法实现:
import java.util.Scanner; public class Main { final String Y = "YES"; final String N = "NO"; public String isPalindrome(String input) { if (input == null || "".equals(input)) { return Y; } int length = input.length(); //题目说明不超过10个字符,那么超过的话,直接返回NO if (length > 10) return N; StringBuilder sb = new StringBuilder(input); for (int i = 0; i < length; i++) { sb.deleteCharAt(i); String temp = sb.toString(); if (sb.reverse().toString().equals(temp)) { return Y; } else { sb = new StringBuilder(input); continue; } } return N; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); String input; while (cin.hasNext()) { input = cin.next(); System.out.println(new Main().isPalindrome(input)); } } }
小蘑的时间假设为[a,b],小菇的时间假设是[c+t,d+t],小菇起床的时间是t∈[l,r],那么当"a < b < (c+t) < (d+t)"或者"(c+t) < (d+t) < a < b"的情况时,小蘑和小菇无法聊天,由题目条件已知"a < b"和"c < d",那么推出"(c+t) < (d+t)",所以仅仅当"b < (c+t)"或者"(d+t) < a"时无法聊天,其余情况都是可以聊天的。
Java算法实现:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNextInt()) { int p = 0, q = 0, l = 0, r = 0; p = cin.nextInt(); q = cin.nextInt(); l = cin.nextInt(); r = cin.nextInt(); int[] time_A_B = new int[p * 2];//标识小蘑的时间 int[] time_C_D = new int[q * 2];//标识小菇的时间 for (int i = 0; i < time_A_B.length; i++) { int temp = cin.nextInt(); time_A_B[i] = temp; } for (int i = 0; i < time_C_D.length; i++) { int temp = cin.nextInt(); time_C_D[i] = temp; } int count = 0;//标识小菇能有多少个合适的起床时间 begin: for (int t = l; t <= r; t++) { for (int i = 0; i < time_A_B.length; i += 2) { for (int j = 0; j < time_C_D.length; j += 2) { if (!(time_C_D[j] + t > time_A_B[i + 1] || time_C_D[j + 1] + t < time_A_B[i])) { count++; continue begin; } } } } System.out.println(count); } } }
如果两个圆刚好相切,那么只需要以切点为固定点旋转;如果两个圆刚好相交,那么只需要以交点为固定点旋转。所以,旋转的次数=圆心之间的距离/2r,距离不足2r的按照一次计算。
Java算法实现:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while (cin.hasNextInt()) { int r = cin.nextInt(); int x = cin.nextInt(); int y = cin.nextInt(); int x1 = cin.nextInt(); int y1 = cin.nextInt(); double length = Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)); int count; //向上取整之后强转为int型即可 count = (int) Math.ceil(length / (2 * r )); System.out.println(count); } } }