329美的集团笔试java编程题记录
1.判断一个字符串中是否存在重复的长度为 N 的子串,如果存在,则输出第一个重复的子串,否则输出 "NO"
示例:查找 "abcdeabc" 中是否有重复的 长度为 3 的子串。
abcdeabc 3
"abc"
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String input = in.nextLine(); String str = input.split(" ")[0]; int N = Integer.parseInt(input.split(" ")[1]); if(N>=str.length() || N==0 ||str==null){ System.out.println("NO"); return; } boolean flag = false; char[] s = str.toCharArray(); Set<String> set = new HashSet<>(); int j; String ans = new String(); for(int i=0; i<=s.length-N; i++){ j=i+N-1; ans = str.substring(i,j+1); if( set.add(ans)==false ){ flag = true; break; } } if(flag){ System.out.println(ans); return; } else{ System.out.println("NO"); return; } } }
2.str1去掉字母只保留数字,然后加上str2和str3的值,最后输出String形式的和(题目不是这样写的,但是意思就是这样)
示例:
ab123c,30,4.5
"157.5"
- str1 = "abc123"
- str2 = "30"
- str3 = "4.5"
- N1 = 123(去掉 "abc" 后的数字部分)
- N2 = 30 + 4.5 = 34.5
- N = 123 + 34.5 = 157.5
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String input = in.nextLine(); String str1 = input.split(",")[0]; String str2 = input.split(",")[1]; String str3 = input.split(",")[2]; Double N2 = Double.parseDouble(str2) + Double.parseDouble(str3); Double N1 = Double.parseDouble( str1.replaceAll("[^0-9]","") ); Double N = N1+N2; System.out.println(N.toString()); } }
3.二维坐标平面上有n个点,保证不存在三点共线,现在需要通过指定两个点连成一条直线,求出被这条直线划分的两个部分各有几个点。
输入描述: 第一行一个正整数n,表示点的个数 接下来的n行:每行两个正整数,表示第i个点的坐标xi、yi 接下来的一行是由两个正整数a,b,表示选择连线的两个点的下标, 1<=a,b<=n, a不等于b 输出描述: 两个数,表示两部分个有几个点,升序输出 实例1
5 1 1 2 3 4 6 5 8 6 10 1 2
0 3
gpt说:”
平面上三点p1(x1,y1) p2(x2,y2) p(x,y),判断p在直线p1p2的哪一侧,
向量p1p2 = (x2-x1,y2-y1) ,向量p1p=(x-x1,y-y1)
以上两向量叉积crossProduct =(x2-x1)*(y-y1)-(y2-y1)*(x-x1)
crossProduct > 0:P在直线 p1p2左侧
crossProduct < 0:P 在直线p1p2 右侧
crossProduct = 0:P在直线p1p2上
“
GPT写的!我积累一下。
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); int[][] points = new int[n][2]; for(int i=0;i<n;i++){ points[i][0]=in.nextInt(); points[i][1]=in.nextInt(); in.nextLine(); } int a = in.nextInt() - 1; int b = in.nextInt() - 1; int x1 = points[a][0], y1 = points[a][1]; int x2 = points[b][0], y2 = points[b][1]; int left =0,right = 0; for(int i=0;i<n;i++){ if(i==a || i==b) continue; int x = points[i][0],y = points[i][1]; long crossProduct = (long)(x2-x1)*(y-y1)-(long)(y2-y1)*(x-x1); if(crossProduct >0){ left++; }else{ right++; } } System.out.println(Math.min(left,right) + " " + Math.max(left,right)); } }