题目描述:
小强正在参加《密室逃生》游戏,当前关卡要求找到符合给定 密码K(升序的不重复小写字母组成)的箱子,并给出箱子编号,箱子编号为1~N。
每个箱子中都有一个字符串s,字符串由大写字母,小写字母,数字,标点符号,空格组成,需要在这些字符串中找出所有的字母,忽略大小写后排列出对应的密码串,并返回匹配密码的箱子序号
提示:
满足条件的箱子不超过1个
输入描述:
第一行为key的字符串,第二行为箱子boxes,为数组样式,以空格分隔
箱子N数量满足1<=N<=10000,
s长度满足 0<=s.length<=50,
密码为仅包含小写字母的升序字符串,且不存在重复字母,
密码K长度K.length,1<=K.length<=26
输出描述:
返回对应箱子编号
如不存在符合要求的密码箱,则返回-1
补充说明:
箱子中字符拼出的字符串与密码的匹配忽略大小写,且要求与密码完全匹配,如密码abc匹配aBc,但是密码abc不匹配abcd
收起
示例1
输入:
abc
s,sdf134 A2c4b
输出:
2
说明:
第2个箱子中的Abc,符合密码abc
示例2
输入:
abc
s,sdf134 A2c4bd 523[]
输出:
-1
说明:
第2个箱子中的Abcd,与密码不完全匹配,不符合要求
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
char[] pwd = in.nextLine().toCharArray();
String input = in.nextLine();
String[] box = input.split(" ");
boolean getMatch = false;
for (int i = 0; i < box.length; i++) {
char[] result = box[i].replaceAll("[^(A-Za-z)]","").toLowerCase().toCharArray();
Arrays.sort(result);
if (isPwdCorrect(pwd, result)) {
getMatch = true;
System.out.println(i + 1);
}
}
if (!getMatch) {
System.out.println("-1");
}
}
}
private static boolean isPwdCorrect(char[] pwd, char[] input) {
if (pwd.length != input.length) {
return false;
}
for (int i = 0; i < pwd.length; i++) {
if (pwd[i] != input[i]) {
return false;
}
}
return true;
}
}
import re
key = input().lower()
boxes = list(input().split())
matched = False
for i in range(len(boxes)):
if len(boxes[i]) > 50:
pass
password = "".join(sorted(list(set("".join(re.findall('[a-zA-Z]', boxes[i])).lower()))))
if password == key:
print(i + 1)
matched = True
break
if not matched:
print(-1)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
string key;
vector<string> arr;
//arr.resize(10000);
cin>>key;
string tmp,trs;
//int count = 0;
while(cin>>tmp){
//arr[count++] = tmp;
arr.push_back(tmp);
}
for (int i = 0; i<arr.size(); ++i){
tmp.assign(arr[i]);
trs.clear();
for(int j=0; j<tmp.size();++j){
char val = tmp[j];
if (val >= 'a' && val <= 'z' ){
trs += tmp[j];
} else if (val >= 'A' && val <= 'Z') {
trs += (val - 'A' + 'a');
} else {
continue;
}
}
//paixu
bool A[26] = {false};
for(int m=0;m<trs.size();++m){
A[trs.at(m) - 'a'] = true;
}
trs.clear();
for(int n=0;n<26;++n){
if(A[n] == true){
trs+=('a'+n);
}
}
arr[i] = trs;
}
for(int i=0; i<arr.size();++i){
if (arr[i].length() != key.length()) continue;
for(int j=0; j<key.length();++j){
if (key.at(j) != arr[i].at(j)) break;
if (j == key.length()-1){
cout<<i+1<<endl;
return 0;
}
}
}
cout<<-1<<endl;
return 0;
}