订单分类
[题目链接](https://www.nowcoder.com/practice/6c685c2ff88043989c09ba9c10785f0a)
思路
给定若干订单 ID(由字母、数字和特殊字符组成),根据首字符类型和剩余字符的组成进行分类。这是一道字符串模拟题,按规则逐条判断即可。
分类规则
设 ID 的第一个字符为 first,剩余部分为 rest:
- electronics:
first是字母,且rest非空且全为数字。 - clothing:
first是数字,且rest非空且全为字母。 - accessories:
first是字母,且rest全为字母或数字(包括rest为空的情况,此时只有一个字母也满足)。 - invalid:
first是数字,且rest非空且全为特殊字符(非字母非数字)。 - miscellaneous:不满足以上任何规则。
注意 electronics 是 accessories 的严格子集(都要求首字符为字母、剩余为字母数字),所以必须先判 electronics 再判 accessories。
样例演示
| ID | 首字符 | 剩余部分 | 分类 |
|---|---|---|---|
| E123 | 字母 | 123(全数字) | electronics |
| 456CLOTH | 数字 | 56CLOTH(含数字) | miscellaneous |
| A1B2C3 | 字母 | 1B2C3(字母+数字) | accessories |
| 1$%^ | 数字 | $%^(全特殊) | invalid |
| A!23 | 字母 | !23(含特殊字符) | miscellaneous |
复杂度分析
- 时间复杂度:
,其中
为订单数,
为 ID 的平均长度。每个 ID 遍历一次字符。
- 空间复杂度:
,存储单个 ID 字符串。
代码
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
string s;
cin >> s;
char first = s[0];
string rest = s.substr(1);
if (isalpha(first)) {
bool allDigits = true, allAlnum = true;
for (char c : rest) {
if (!isdigit(c)) allDigits = false;
if (!isalnum(c)) allAlnum = false;
}
if (!rest.empty() && allDigits) cout << "electronics" << endl;
else if (allAlnum) cout << "accessories" << endl;
else cout << "miscellaneous" << endl;
} else if (isdigit(first)) {
bool allAlpha = true, allSpecial = true;
for (char c : rest) {
if (!isalpha(c)) allAlpha = false;
if (isalnum(c)) allSpecial = false;
}
if (!rest.empty() && allAlpha) cout << "clothing" << endl;
else if (!rest.empty() && allSpecial) cout << "invalid" << endl;
else cout << "miscellaneous" << endl;
} else {
cout << "miscellaneous" << endl;
}
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String s = sc.next();
char first = s.charAt(0);
String rest = s.substring(1);
if (Character.isLetter(first)) {
boolean allDigits = true, allAlnum = true;
for (int j = 0; j < rest.length(); j++) {
char c = rest.charAt(j);
if (!Character.isDigit(c)) allDigits = false;
if (!Character.isLetterOrDigit(c)) allAlnum = false;
}
if (rest.length() > 0 && allDigits) System.out.println("electronics");
else if (allAlnum) System.out.println("accessories");
else System.out.println("miscellaneous");
} else if (Character.isDigit(first)) {
boolean allAlpha = true, allSpecial = true;
for (int j = 0; j < rest.length(); j++) {
char c = rest.charAt(j);
if (!Character.isLetter(c)) allAlpha = false;
if (Character.isLetterOrDigit(c)) allSpecial = false;
}
if (rest.length() > 0 && allAlpha) System.out.println("clothing");
else if (rest.length() > 0 && allSpecial) System.out.println("invalid");
else System.out.println("miscellaneous");
} else {
System.out.println("miscellaneous");
}
}
}
}

京公网安备 11010502036488号