java-python-code-reviewer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Java & Python Code Reviewer

Java & Python 代码审查工具

When to use this Skill

何时使用本工具

Use this Skill when:
  • Reviewing LeetCode problem solutions
  • Checking code correctness and efficiency
  • Comparing Java and Python implementations
  • Providing feedback on algorithm implementations
  • Optimizing existing solutions
在以下场景使用本工具:
  • 审查LeetCode问题解决方案
  • 检查代码的正确性与效率
  • 对比Java和Python实现方案
  • 为算法实现提供反馈
  • 优化现有解决方案

Review Framework

审查框架

1. Correctness Analysis

1. 正确性分析

Check for:
  • Edge cases handling (empty input, null, single element)
  • Boundary conditions (array indices, loop termination)
  • Logic errors in algorithm implementation
  • Test case coverage (basic, edge, corner cases)
Common edge cases:
  • Empty arrays/strings:
    []
    ,
    ""
  • Null inputs:
    null
    ,
    None
  • Single element:
    [1]
    ,
    "a"
  • Duplicates:
    [1,1,1]
  • Negative numbers:
    [-1, -5]
  • Large inputs: Test time/space limits
检查要点:
  • 边界情况处理(空输入、null、单个元素)
  • 边界条件(数组索引、循环终止)
  • 算法实现中的逻辑错误
  • 测试用例覆盖度(基础用例、边界用例、极端用例)
常见边界情况:
  • 空数组/字符串:
    []
    ,
    ""
  • 空值输入:
    null
    ,
    None
  • 单个元素:
    [1]
    ,
    "a"
  • 重复元素:
    [1,1,1]
  • 负数:
    [-1, -5]
  • 大输入量:测试时间/空间限制

2. Time & Space Complexity

2. 时间与空间复杂度

Analyze and verify:
  • Time complexity: Count operations relative to input size
  • Space complexity: Count auxiliary space used
  • Compare against optimal solution
Provide:
Current: O(n²) time, O(1) space
Optimal: O(n) time, O(n) space using HashMap
Trade-off: Use extra space for better time complexity
Complexity Reference:
  • O(1): Direct access
  • O(log n): Binary search, balanced tree
  • O(n): Single pass, linear scan
  • O(n log n): Efficient sorting, divide-and-conquer
  • O(n²): Nested loops
  • O(2ⁿ): Exponential (backtracking, brute force)
分析与验证:
  • 时间复杂度:统计与输入规模相关的操作次数
  • 空间复杂度:统计使用的辅助空间
  • 与最优方案对比
输出示例:
当前:O(n²) 时间复杂度,O(1) 空间复杂度
最优:使用HashMap实现O(n)时间复杂度、O(n)空间复杂度
权衡:用额外空间换取更优的时间复杂度
复杂度参考:
  • O(1):直接访问
  • O(log n):二分查找、平衡树
  • O(n):单次遍历、线性扫描
  • O(n log n):高效排序、分治法
  • O(n²):嵌套循环
  • O(2ⁿ):指数级(回溯、暴力法)

3. Code Quality - Java

3. Java代码质量

Java Best Practices:
  • Use appropriate data structures (
    ArrayList
    ,
    HashMap
    ,
    HashSet
    )
  • Follow naming conventions (camelCase for methods/variables)
  • Handle null checks and validation
  • Use generics properly (
    List<Integer>
    not raw types)
  • Prefer interfaces over implementations (
    List<>
    not
    ArrayList<>
    )
Java Anti-patterns to flag:
java
// Bad: Raw types
ArrayList list = new ArrayList();

// Good: Generics
List<Integer> list = new ArrayList<>();

// Bad: Manual array copying
for (int i = 0; i < arr.length; i++) { ... }

// Good: Built-in methods
Arrays.copyOf(arr, arr.length);

// Bad: String concatenation in loop
String s = "";
for (String str : list) { s += str; }

// Good: StringBuilder
StringBuilder sb = new StringBuilder();
for (String str : list) { sb.append(str); }
Check for:
  • Integer overflow: Suggest
    long
    when needed
  • Proper exception handling
  • Memory leaks (unclosed resources)
  • Thread safety if applicable
Java最佳实践:
  • 使用合适的数据结构(
    ArrayList
    ,
    HashMap
    ,
    HashSet
  • 遵循命名规范(方法/变量使用小驼峰)
  • 处理空值检查与验证
  • 正确使用泛型(
    List<Integer>
    而非原始类型)
  • 优先使用接口而非实现类(
    List<>
    而非
    ArrayList<>
需要标记的Java反模式:
java
// 不良写法:原始类型
ArrayList list = new ArrayList();

// 推荐写法:泛型
List<Integer> list = new ArrayList<>();

// 不良写法:手动数组复制
for (int i = 0; i < arr.length; i++) { ... }

// 推荐写法:内置方法
Arrays.copyOf(arr, arr.length);

// 不良写法:循环中拼接字符串
String s = "";
for (String str : list) { s += str; }

// 推荐写法:StringBuilder
StringBuilder sb = new StringBuilder();
for (String str : list) { sb.append(str); }
检查要点:
  • 整数溢出:必要时建议使用
    long
    类型
  • 正确的异常处理
  • 内存泄漏(未关闭的资源)
  • 若涉及多线程,需检查线程安全性

4. Code Quality - Python

4. Python代码质量

Python Best Practices:
  • Use Pythonic idioms (list comprehensions, enumerate, zip)
  • Follow PEP 8 style guidelines
  • Use appropriate data structures (
    set
    ,
    dict
    ,
    deque
    )
  • Leverage built-in functions
Python Anti-patterns to flag:
python
undefined
Python最佳实践:
  • 使用Pythonic写法(列表推导式、enumerate、zip)
  • 遵循PEP 8风格指南
  • 使用合适的数据结构(
    set
    ,
    dict
    ,
    deque
  • 充分利用内置函数
需要标记的Python反模式:
python
undefined

Bad: Manual index tracking

不良写法:手动跟踪索引

for i in range(len(arr)): print(i, arr[i])
for i in range(len(arr)): print(i, arr[i])

Good: enumerate

推荐写法:enumerate

for i, val in enumerate(arr): print(i, val)
for i, val in enumerate(arr): print(i, val)

Bad: Building list with append in loop

不良写法:循环中用append构建列表

result = [] for x in arr: result.append(x * 2)
result = [] for x in arr: result.append(x * 2)

Good: List comprehension

推荐写法:列表推导式

result = [x * 2 for x in arr]
result = [x * 2 for x in arr]

Bad: Multiple membership checks

不良写法:多条件成员检查

if x == 'a' or x == 'b' or x == 'c':
if x == 'a' or x == 'b' or x == 'c':

Good: Use set or tuple

推荐写法:使用集合或元组

if x in {'a', 'b', 'c'}:

**Check for:**
- Use of appropriate collections (`collections.defaultdict`, `Counter`)
- Generator expressions for memory efficiency
- Proper use of `None` checks
- Type hints for clarity (optional but helpful)
if x in {'a', 'b', 'c'}:

**检查要点:**
- 合适的集合类使用(`collections.defaultdict`, `Counter`)
- 使用生成器表达式提升内存效率
- 正确的`None`值检查
- 类型提示增强代码清晰度(可选但推荐)

5. Algorithm Optimization

5. 算法优化

Suggest improvements for:
  • Unnecessary nested loops → Use HashMap for O(n)
  • Repeated calculations → Use memoization/DP
  • Redundant sorting → Use heap or quick select
  • Multiple passes → Combine into single pass
  • Extra space usage → In-place modifications
Pattern Recognition:
  • Two Sum pattern → Use HashMap
  • Sliding Window → Two pointers
  • Subarray sum → Prefix sum
  • Longest substring → Sliding window + HashMap
  • Tree traversal → DFS/BFS with proper data structure
建议优化方向:
  • 不必要的嵌套循环 → 使用HashMap实现O(n)复杂度
  • 重复计算 → 使用记忆化/动态规划
  • 冗余排序 → 使用堆或快速选择
  • 多次遍历 → 合并为单次遍历
  • 额外空间占用 → 原地修改
模式识别:
  • 两数之和模式 → 使用HashMap
  • 滑动窗口 → 双指针
  • 子数组和 → 前缀和
  • 最长子串 → 滑动窗口+HashMap
  • 树遍历 → 搭配合适数据结构的DFS/BFS

6. Comparison: Java vs Python

6. 对比:Java vs Python

When comparing implementations:
Java strengths:
  • Explicit types catch errors early
  • Better for performance-critical code
  • Clear data structure usage
Python strengths:
  • More concise and readable
  • Rich standard library (collections, itertools)
  • Better for rapid prototyping
Flag inconsistencies:
  • Different algorithms used (should be same approach)
  • Different time/space complexity
  • Missing edge case handling in one version
对比实现方案时:
Java优势:
  • 显式类型提前捕获错误
  • 更适合性能敏感型代码
  • 数据结构使用清晰
Python优势:
  • 代码更简洁易读
  • 丰富的标准库(collections、itertools)
  • 更适合快速原型开发
需要标记的不一致点:
  • 使用了不同的算法(应保持同一思路)
  • 时间/空间复杂度不同
  • 其中一个版本遗漏了边界情况处理

7. Review Output Format

7. 审查输出格式

Structure your review as:
markdown
undefined
审查结果请按以下结构整理:
markdown
undefined

Correctness: ✓ Pass / ⚠ Issues Found

正确性:✓ 通过 / ⚠ 发现问题

[List any correctness issues]
[列出所有正确性问题]

Complexity Analysis

复杂度分析

  • Time: O(?) - [Explain]
  • Space: O(?) - [Explain]
  • Optimal: [If current solution is not optimal]
  • 时间:O(?) - [说明]
  • 空间:O(?) - [说明]
  • 最优方案:[若当前方案非最优]

Code Quality

代码质量

Strengths:
  • [List positive aspects]
Issues:
  • [Issue 1] at line X: [Explanation]
  • [Issue 2] at line Y: [Explanation]
Suggestions:
  • [Suggestion 1]: [Why it's better]
  • [Suggestion 2]: [Why it's better]
优点:
  • [列出积极方面]
问题:
  • [问题1] 位于第X行:[说明]
  • [问题2] 位于第Y行:[说明]
建议:
  • [建议1]:[为何更优]
  • [建议2]:[为何更优]

Overall Assessment

整体评估

[Summary and recommendation]
undefined
[总结与建议]
undefined

Review Checklist

项目上下文

Before completing review:
  • Tested with edge cases
  • Verified time complexity
  • Verified space complexity
  • Checked for common bugs
  • Compared to optimal solution
  • Suggested concrete improvements
  • Provided code examples for suggestions
  • 审查
    leetcode_java/
    leetcode_python/
    目录下的解决方案
  • 跨语言对比实现方案
  • 对照
    algorithm/
    data_structure/
    目录下的模式
  • 参考
    doc/
    目录下的复杂度图表进行分析

Example Reviews

Example 1: Two Sum

java
// Code under review
public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                return new int[]{i, j};
            }
        }
    }
    return new int[]{};
}
Review:
  • Correctness: ✓ Works correctly
  • Time: O(n²) - Can be optimized to O(n)
  • Suggestion: Use HashMap to store seen numbers and their indices
Optimized:
java
public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[]{map.get(complement), i};
        }
        map.put(nums[i], i);
    }
    return new int[]{};
}

Project Context

  • Review solutions in
    leetcode_java/
    and
    leetcode_python/
  • Compare implementations across languages
  • Check against patterns in
    algorithm/
    and
    data_structure/
  • Reference complexity charts in
    doc/
    for analysis