赞
踩
提取字符串中的最长合法简单数学表达式,字符串长度最长的,并计算表达式的值,如果没有返回0。简单数学表达式只能包含以下内容0-9 数字,符号+-*/
说明:
1.所有数字,计算结果都不超过 long
2.如果有多个长度一样的,请返回第一个表达式的结果
3.数学表达式,必须是最长的,合法的
4.操作符不能连续出现,如 +--+1 是不合法的
输入
字符串
输出
表达式值
示例一
输入
1-2abcd
输出
-1
示例二
输入
1-2abs1-2*3+7dd4-5+6
输出
2
示例三
输入
a1/0+8d
输出
8
这道题有点难度,有以下几个难点:
1、如何找出最长合法表达式?
2、如何计算该表达式?
3、四则运算有一种特殊情况,除数不为零,这种也必须考虑。
上述三个问题的对应解法:
1、用正则表达式筛选表达式。
2、用递归方法计算,主要优势代码简洁。下面链接有详细说明。四则运算字符串计算数值-Java解法https://blog.csdn.net/weixin_43389472/article/details/135962943
3、将 “/0” 替换为“a0”,这样既不影响前面表达式也不影响后面,注意这个“0”是不能去掉的,会造成后面表达式的不合法,如上述 示例三 一样。
解法如下:
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- public class Main {
-
- public static void main(String[] args) {
-
- Scanner scanner = new Scanner(System.in);
- String str = scanner.nextLine();
-
- String longStr = dealWith(str);
-
- if (!longStr.isEmpty()) {
-
- int result = calculate(longStr);
- System.out.println(result);
-
- } else {
- System.out.println(0);
- }
-
-
- }
-
- //判断字符串是否只有数字
- private static boolean isNumber(String str) {
- for (int i = 0; i < str.length(); i++) {
- if (!Character.isDigit(str.charAt(i))) {
- return false;
- }
- }
- return true;
- }
-
- //利用递归方法计算四则运算
- private static int calculate(String str) {
-
- if (isNumber(str)) {
- return Integer.parseInt(str);
- }
-
- if (str.contains("+")) {
- int index = str.indexOf("+");
- return calculate(str.substring(0, index)) + calculate(str.substring(index + 1));
- }
-
- if (str.contains("-")) {
- int index = str.indexOf("-");
- return calculate(str.substring(0, index)) - calculate(str.substring(index + 1));
- }
-
- if (str.contains("*")) {
- int index = str.indexOf("*");
- return calculate(str.substring(0, index)) * calculate(str.substring(index + 1));
- }
-
- if (str.contains("/")) {
- int index = str.indexOf("/");
- return calculate(str.substring(0, index)) / calculate(str.substring(index + 1));
- }
- return 0;
- }
-
- //借助正则表达式拆出符合要求的表达式
- private static String dealWith(String str) {
-
- //将除数等于0替换掉,注意string是不可变量,所以要用新的变量代替
- String replaceStr = str.replace("/0", "a0");
-
- int max = 0;
- String longStr = "";
- String regex = "\\d+([\\+\\-*/]\\d+)+";
-
- Pattern compile = Pattern.compile(regex);
- Matcher matcher = compile.matcher(replaceStr);
-
- while (matcher.find()) {
- String group = matcher.group();
- if (group.length() > max) {
- max = group.length();
- longStr = group;
- }
-
- }
- return longStr;
- }
-
-
- }
欢迎大家留言讨论。
注:题目源自 梦想橡皮擦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。