题解 | 身份证分组

身份证分组

https://www.nowcoder.com/practice/58766632a6cc45c0a1158fea2db91728

解题思路

  1. 基本思路:

    • 根据身份证号长度进行分组
    • 按照 的格式添加空格
    • 处理不同长度的输入情况
  2. 实现方法:

    • 遍历字符串
    • 在第 位和第 位后添加空格
    • 处理长度不足的情况

代码

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string formatIdCard(string input) {
        string result = input;
        
        // 添加第一个空格(第6位后)
        if (input.length() > 6) {
            result.insert(6, " ");
        }
        
        // 添加第二个空格(第14位后,考虑已插入的空格)
        if (input.length() > 14) {
            result.insert(15, " ");
        }
        
        return result;
    }
};

int main() {
    string input;
    Solution solution;
    
    while (getline(cin, input)) {
        cout << solution.formatIdCard(input) << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    public static String formatIdCard(String input) {
        StringBuilder result = new StringBuilder(input);
        
        // 添加第一个空格(第6位后)
        if (input.length() > 6) {
            result.insert(6, " ");
        }
        
        // 添加第二个空格(第14位后,考虑已插入的空格)
        if (input.length() > 14) {
            result.insert(15, " ");
        }
        
        return result.toString();
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextLine()) {
            String input = sc.nextLine();
            System.out.println(formatIdCard(input));
        }
    }
}
class Solution:
    def formatIdCard(self, input_str):
        result = list(input_str)
        
        # 添加第一个空格(第6位后)
        if len(input_str) > 6:
            result.insert(6, " ")
        
        # 添加第二个空格(第14位后,考虑已插入的空格)
        if len(input_str) > 14:
            result.insert(15, " ")
        
        return "".join(result)

if __name__ == "__main__":
    solution = Solution()
    try:
        while True:
            input_str = input().strip()
            print(solution.formatIdCard(input_str))
    except:
        pass

算法及复杂度

  • 算法:字符串处理
  • 时间复杂度:,其中 为字符串长度
  • 空间复杂度:,用于存储结果字符串
全部评论

相关推荐

若怜君欢:驾驶证去掉吧,PPT啥的也去掉,本硕课程去掉,导师和研究方向去掉;加入本硕排名(好才写);技能栏加入你会的那些控制算法和滤波算法,这个比你会啥啥啥软件更有用;获奖写上去,奖学金啊,有没有专利啊之类的 电机和硬件这一块,属于传统制造业,制造业实习并不多。多投一些攒攒经验,有实习最好,没有也不需要焦虑(制造业实习其实除了转正,没多大用处) 最后,划重点,等秋招开始后,把你所有社交软件都发一份简历上去,并经常更新,找人内推你!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务