包裹分类
[题目链接](https://www.nowcoder.com/practice/ca6a720517b64ae08b53ea86af9eabb4)
思路
本题是一道字符串分类模拟题,根据包裹 ID 的首字符和剩余字符的组成来判断类别。
分类规则梳理
按首字符分两大情况讨论:
- 首字符是字母:
- 剩余字符全是数字 → standard
- 剩余字符既有字母又有数字 → mix
- 其他(含特殊字符,或剩余全是字母) → invalid
- 首字符是数字:
- 剩余字符全是字母 → special
- 否则 → invalid
- 首字符既不是字母也不是数字 →
invalid
实现要点
遍历 ID 中除首字符外的所有字符,统计是否包含数字、字母、其他字符,然后根据上述规则输出对应类别即可。
代码
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
string s;
cin >> s;
if (isalpha(s[0])) {
bool hasDigit = false, hasAlpha = false, hasOther = false;
for (int i = 1; i < (int)s.size(); i++) {
if (isdigit(s[i])) hasDigit = true;
else if (isalpha(s[i])) hasAlpha = true;
else hasOther = true;
}
if (hasOther) cout << "invalid" << endl;
else if (hasDigit && !hasAlpha) cout << "standard" << endl;
else if (hasDigit && hasAlpha) cout << "mix" << endl;
else cout << "invalid" << endl;
} else if (isdigit(s[0])) {
bool allAlpha = true;
for (int i = 1; i < (int)s.size(); i++) {
if (!isalpha(s[i])) { allAlpha = false; break; }
}
cout << (allAlpha ? "special" : "invalid") << endl;
} else {
cout << "invalid" << 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();
while (n-- > 0) {
String s = sc.next();
char first = s.charAt(0);
if (Character.isLetter(first)) {
boolean hasDigit = false, hasAlpha = false, hasOther = false;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) hasDigit = true;
else if (Character.isLetter(c)) hasAlpha = true;
else hasOther = true;
}
if (hasOther) System.out.println("invalid");
else if (hasDigit && !hasAlpha) System.out.println("standard");
else if (hasDigit && hasAlpha) System.out.println("mix");
else System.out.println("invalid");
} else if (Character.isDigit(first)) {
boolean allAlpha = true;
for (int i = 1; i < s.length(); i++) {
if (!Character.isLetter(s.charAt(i))) { allAlpha = false; break; }
}
System.out.println(allAlpha ? "special" : "invalid");
} else {
System.out.println("invalid");
}
}
}
}
复杂度分析
设 为包裹数量,
为 ID 的平均长度。
- 时间复杂度:
,每个 ID 遍历一次所有字符。
- 空间复杂度:
,存储当前读入的字符串。

京公网安备 11010502036488号