科大讯飞2020校招笔试题及答案

第一题:
实现一个加法计数器,要求满足是任意大小的两个整数相加
输入描述:任意大小的两个整数
输出描述:相加的结果
输入示例:123456789987654321 987654321123456789
输出示例:1111111111111111110

这是做的所有笔试题中,输入代码最短但是AC的。有点不信。我当时想着时间不够了,就用的满足部分案例的方法,意外AC了。
其实题目本意应该是想让我们用字符串处理的。后面再补充。

package com.test;

import java.math.BigInteger;
import java.util.*;

public class Test4 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s1 = sc.next();
		String s2 = sc.next();
		BigInteger b1 = new BigInteger(s1);
		BigInteger b2 = new BigInteger(s2);
		System.out.println(b1.add(b2));
		
	}
	
}

第二题:压缩字符串
将任意长度的字符串按下列规则压缩并输出
规则:相同连续的字符,则压缩为“数字个数 + 字符”,如aaabb输出3a2b
输入示例:aabb
输出示例:2a2b
备注:单个不压缩,如abcdba,输入不包含数字和转义字符

package com.test;

import java.util.*;

public class Test4 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		System.out.println(resolve(s));
		
	}
	
	static String resolve(String str) {
		char pre = '\0';
		int count = 0;
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			char cur = str.charAt(i);
			if (cur == pre) {
				count++;
			} else {
				if (pre != '\0') {
					if(count > 1) {
						result.append(count);
					}
					result.append(pre);
				}
				pre = cur;
				count = 1;
			}
		}
		if (pre != '\0') {
			if(count > 1) {
				result.append(count);
			}
			result.append(pre);
		}
		return result.toString();
	}
	
}

这里用栈解决第二题:

package com.test;

import java.util.Scanner;
import java.util.Stack;

public class Test5 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		Stack<Character> stack = new Stack<Character>();
		int count = 1;
		for (int i = 0; i < s.length(); i++) {
			if (!stack.isEmpty()) {
				if (s.charAt(i) == stack.peek()) {
					count++;
					stack.pop();
					stack.pop();
				} else {
					count = 1;
				}
				char c = (char) ('0' + count);
				stack.push(c);
				stack.push(s.charAt(i));				
			} else {
				stack.push('1');
				stack.push(s.charAt(i));
			}
		}

		//System.out.println(stack);
		StringBuilder result = new StringBuilder();
		while(!stack.isEmpty()) {
			if (stack.peek() != '1') {
				result.insert(0, stack.pop());
			} else {
				stack.pop();
			}
		}
		System.out.println(result.toString());
		
	}
}

你可能感兴趣的:(编程题)