提取字符串中的最长数学表达式并计算(67用例) C卷(Java&&Python&&C++&&Node.js&&C语言)

提取字符串中的最长合法简单数学表达式,字符串长度最长的,并计算表达式的值。如果没有,则返回0

简单数学表达式只能包含以下内容

0-9数字,符号+-*

说明:

1.所有数字,计算结果都不超过long

2.如果有多个长度一样的,请返回第一个表达式的结果

3.数学表达式,必须是最长的,合法的

4.操作符不能连续出现,如+--+1是不合法的

输入描述:

复制代码
字符串<

输出描述:

复制代码
表达式值

示例1 输入输出示例仅供调试,后台判题数据一般不包含示例

输入

复制代码
1-2abcd

输出

复制代码
-1

Java版本

java 复制代码
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        long res = 0;
        int maxLen = 0;
        int len = line.length();
        for (int i = 0; i < len; i++) {
            if (len - i <= maxLen) {
                break;
            }
            for (int j = i; j < len; j++) {
                String sub = line.substring(i, j + 1);
                Matcher matcher = Pattern.compile("(\\d+)([*+-])(\\d+)").matcher(sub);
                if (matcher.find() && j + 1 - i > maxLen) {
                    maxLen = j + 1 - i;
                    long first = Long.parseLong(matcher.group(1));
                    String op = matcher.group(2);
                    long second = Long.parseLong(matcher.group(3));
                    switch (op) {
                        case "+":
                            res = first + second;
                            break;
                        case "-":
                            res = first - second;
                            break;
                        case "*":
                            res = first * second;
                            break;
                    }
                }
            }
        }
        System.out.println(res);
    }
}

Python版本

python 复制代码
import re

line = input()
res = 0
max_len = 0
length = len(line)

for i in range(length):
    if length - i <= max_len:
        break
    for j in range(i, length):
        sub = line[i:j+1]
        match = re.search(r'(\d+)([*+-])(\d+)', sub)
        if match and j + 1 - i > max_len:
            max_len = j + 1 - i
            first = int(match.group(1))
            op = match.group(2)
            second = int(match.group(3))
            if op == '+':
                res = first + second
            elif op == '-':
                res = first - second
            elif op == '*':
                res = first * second

print(res)

C++版本

cpp 复制代码
#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    string line;
    getline(cin, line);
    long long res = 0;
    int maxLen = 0;
    int len = line.length();
    for (int i = 0; i < len; i++) {
        if (len - i <= maxLen) {
            break;
        }
        for (int j = i; j < len; j++) {
            string sub = line.substr(i, j - i + 1);
            smatch match;
            regex pattern("(\\d+)([*+-])(\\d+)");
            if (regex_search(sub, match, pattern) && j + 1 - i > maxLen) {
                maxLen = j + 1 - i;
                long long first = stoll(match[1]);
                string op = match[2];
                long long second = stoll(match[3]);
                if (op == "+") {
                    res = first + second;
                } else if (op == "-") {
                    res = first - second;
                } else if (op == "*") {
                    res = first * second;
                }
            }
        }
    }
    cout << res << endl;
    return 0;
}

C语言版本

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isOperator(char c) {
    return c == '+' || c == '-' || c == '*';
}

long long calculate(long long first, char op, long long second) {
    if (op == '+') {
        return first + second;
    } else if (op == '-') {
        return first - second;
    } else if (op == '*') {
        return first * second;
    }
    return 0;
}

int main() {
    char line[100];
    fgets(line, sizeof(line), stdin);

    long long res = 0;
    int maxLen = 0;
    int len = strlen(line);
    for (int i = 0; i < len; i++) {
        if (len - i <= maxLen) {
            break;
        }
        for (int j = i; j < len; j++) {
            char sub[100];
            strncpy(sub, &line[i], j - i + 1);
            sub[j - i + 1] = '\0';

            long long first, second;
            char op;
            int matched = sscanf(sub, "%lld%c%lld", &first, &op, &second);
            if (matched == 3 && isOperator(op) && j + 1 - i > maxLen) {
                maxLen = j + 1 - i;
                res = calculate(first, op, second);
            }
        }
    }

    printf("%lld\n", res);
    return 0;
}

Node.js版本

javascript 复制代码
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function isOperator(c) {
    return c === '+' || c === '-' || c === '*';
}

function calculate(first, op, second) {
    if (op === '+') {
        return first + second;
    } else if (op === '-') {
        return first - second;
    } else if (op === '*') {
        return first * second;
    }
    return 0;
}

rl.question('Enter a line: ', (line) => {
    let res = 0;
    let maxLen = 0;
    const len = line.length;

    for (let i = 0; i < len; i++) {
        if (len - i <= maxLen) {
            break;
        }
        for (let j = i; j < len; j++) {
            const sub = line.substring(i, j + 1);
            const match = sub.match(/(\d+)([*+-])(\d+)/);
            if (match && j + 1 - i > maxLen) {
                maxLen = j + 1 - i;
                const first = parseInt(match[1]);
                const op = match[2];
                const second = parseInt(match[3]);
                res = calculate(first, op, second);
            }
        }
    }

    console.log(res);
    rl.close();
});
相关推荐
Ysjt | 深2 小时前
C++多线程编程入门教程(优质版)
java·开发语言·jvm·c++
ephemerals__2 小时前
【c++丨STL】list模拟实现(附源码)
开发语言·c++·list
Microsoft Word2 小时前
c++基础语法
开发语言·c++·算法
一只小小汤圆2 小时前
opencascade源码学习之BRepOffsetAPI包 -BRepOffsetAPI_DraftAngle
c++·学习·opencascade
legend_jz3 小时前
【Linux】线程控制
linux·服务器·开发语言·c++·笔记·学习·学习方法
嘿BRE3 小时前
【C++】几个基本容器的模拟实现(string,vector,list,stack,queue,priority_queue)
c++
程楠楠&M3 小时前
node.js第三方Express 框架
前端·javascript·node.js·express
盛夏绽放4 小时前
Node.js 和 Socket.IO 实现实时通信
前端·后端·websocket·node.js
ö Constancy4 小时前
c++ 笔记
开发语言·c++