实习笔试-01字符转换小写字母
题目描述:
根据输入的字符串,按照一定的规则将字母分配给数字字符,并生成一个新的字符串
1. 如果字符串只包含一个数字字符,则所有的字母按顺序分配给该数字字符
2. 如果字符串中包含0和1,则a分配给1,其余的字母按照顺序分配给0
3. 输出字符串是根据输入字符串中的数字字符,依次从对应的字母列表中取出字母拼接而成
输入:01字符串,这里使用String
输出:字符串
思路:
- 先将字符串转换为字符数组
- 存储到Set集合中,判断只有一种字符还是有两种
- 只有一种的话,把所有的小写字母分配给唯一的数字,有两种的话把‘a’分配给1,其他的‘b’-‘z’分配给0
- 然后遍历字符串,用小写字符替换
//然后遍历字符串数组
//使用StringBuilder做拼接
StringBuilder sb = new StringBuilder();
//定义0和1的当前索引
int[] indexs = new int[2];
for(char c : s.toCharArray()){
List<Character> list = map.get(c);
int index = indexs[c - '0'] % list.size();
sb.append(list.get(index));
indexs[c - '0']++;
}
关于字符串拼接:
使用StringBuilder来操作StringBuilder sb = new StringBuilder();
,然后定义一个数组来存储0、1的当前索引int[] indexs = new int[2];
,遍历数组for(char c : s.toCharArray())
,取出当前数字字符对应的小写字母链表List<Character> list = map.get(c)
,然后得到链表中的小写字符int index = indexs[c - '0'] % list.size();
,进行StringBuilder拼接,sb.append(list.get(index));
然后将当前字符指向下一个小写字符indexs[c - '0']++;
import java.util.*;
/**
* @Title: test_Ant_1
* @Author Vacant Seat
* @Date 2025/3/14 17:46
*/
public class test_Ant_1 {
public static void main(String[] args) {
//输入
Scanner sc = new Scanner(System.in);
String s = sc.next();
//调用方法
String s1 = numToChar(s);
System.out.println(s1);
}
private static String numToChar(String s){
Set<Character> set = new HashSet<>();
for(char c : s.toCharArray()){
set.add(c);
}
//定义一个HashMap,用来存储对应的关系
Map<Character,List<Character>> map = new HashMap<>();
//定义两个字符链表,存储小写字母
List<Character> zeroList = new ArrayList<>();
List<Character> oneList = new ArrayList<>();
if(set.size() == 1){
//将所有的字母分配给唯一的数字
char num = set.iterator().next();
//说明此时只有一个数字字符
for(char c = 'a'; c <= 'z'; c++){
zeroList.add(c);
}
//将num和zeroList存入map
map.put(num, zeroList);
}else {
oneList.add('a');
for(char c = 'b'; c <= 'z'; c++){
zeroList.add(c);
}
map.put('1',oneList);
map.put('0',zeroList);
}
//然后遍历字符串数组
//使用StringBuilder做拼接
StringBuilder sb = new StringBuilder();
//定义0和1的当前索引
int[] indexs = new int[2];
for(char c : s.toCharArray()){
List<Character> list = map.get(c);
int index = indexs[c - '0'] % list.size();
sb.append(list.get(index));
indexs[c - '0']++;
}
return sb.toString();
}
}