Skip to content

Latest commit

 

History

History
178 lines (139 loc) · 3.98 KB

1667.md

File metadata and controls

178 lines (139 loc) · 3.98 KB
title description keywords
1667. 修复表中的名字
LeetCode 1667. 修复表中的名字题解,Fix Names in a Table,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
1667. 修复表中的名字
修复表中的名字
Fix Names in a Table
解题思路
数据库

1667. 修复表中的名字

🟢 Easy  🔖  数据库  🔗 力扣 LeetCode

题目

Table: Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+

user_id is the primary key (column with unique values) for this table.

This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.

Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.

Return the result table ordered by user_id.

The result format is in the following example.

Example 1:

Input:

Users table:

+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | aLice |
| 2       | bOB   |
+---------+-------+

Output:

+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | Alice |
| 2       | Bob   |
+---------+-------+

题目大意

表: Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+

user_id 是该表的主键(具有唯一值的列)。

该表包含用户的 ID 和名字。名字仅由小写和大写字符组成。

编写解决方案,修复名字,使得只有第一个字符是大写的,其余都是小写的。

返回按 user_id 排序的结果表。

返回结果格式示例如下。

示例 1:

输入:

Users table:

+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | aLice |
| 2       | bOB   |
+---------+-------+

输出:

+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | Alice |
| 2       | Bob   |
+---------+-------+

解题思路

MySQL

  1. 返回字段
    使用 SELECT 指定返回字段:

    • user_id:用户 ID。
    • 修复后的 name,通过函数计算生成。
  2. 修复名字
    使用 CONCAT 和字符串函数:

    • UPPER(SUBSTRING(name, 1, 1)):将名字的第一个字符转换为大写。
    • LOWER(SUBSTRING(name, 2)):将名字从第二个字符开始的部分转换为小写。
    • 将两部分拼接为正确的名字格式。
  3. 排序要求
    user_id 进行升序排序。

复杂度分析

  • 时间复杂度O(n),假设表中有 n 条记录,需要对每条记录执行字符串操作。
  • 空间复杂度:SQL 查询本身不占用额外空间,返回的结果占用的空间与记录数成正比。

Pandas

  1. 加载数据
    Users 表加载到 Pandas 的 DataFrame 中。

  2. 修复名字
    使用 Pandas 的 str.capitalize() 方法将每个名字的首字母大写,其余字符小写。

  3. 结果选择与排序
    返回结果包含 user_id 和修复后的 name,按 user_id 升序排列。

代码

::: code-tabs @tab MySQL

SELECT user_id,
       CONCAT(UPPER(SUBSTRING(name, 1, 1)), LOWER(SUBSTRING(name, 2))) AS name
FROM Users
ORDER BY user_id;

@tab Pandas

import pandas as pd

def fix_names(users: pd.DataFrame) -> pd.DataFrame:
    # 修复名字格式
    users['name'] = users['name'].str.capitalize()
    # 返回结果并按 user_id 排序
    return users.sort_values(by='user_id')

:::