LeetCode 题解工作台

相等的有理数

给定两个字符串 s 和 t ,每个字符串代表一个非负有理数,只有当它们表示相同的数字时才返回 true 。字符串中可以使用括号来表示有理数的重复部分。 有理数 最多可以用三个部分来表示: 整数部分 、 小数非重复部分 和 小数重复部分 。数字可以用以下三种方法之一来表示: 例: 0 , 12 和 1…

category

2

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

困难 · 数学·string

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个字符串 s 和 t ,每个字符串代表一个非负有理数,只有当它们表示相同的数字时才返回 true 。字符串中可以使用括号来表示有理数的重复部分。

有理数 最多可以用三个部分来表示:整数部分 <IntegerPart>小数非重复部分 <NonRepeatingPart> 和小数重复部分 <(><RepeatingPart><)>。数字可以用以下三种方法之一来表示:

  • <IntegerPart> 
    • 例: 0 ,12 和 123 
  • <IntegerPart><.><NonRepeatingPart>
    • 例: 0.5 , 1. , 2.12 和 123.0001
  • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> 
    • 例: 0.1(6)1.(9)123.00(1212)

十进制展开的重复部分通常在一对圆括号内表示。例如:

  • 1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)

 

示例 1:

输入:s = "0.(52)", t = "0.5(25)"
输出:true
解释:因为 "0.(52)" 代表 0.52525252...,而 "0.5(25)" 代表 0.52525252525.....,则这两个字符串表示相同的数字。

示例 2:

输入:s = "0.1666(6)", t = "0.166(66)"
输出:true

示例 3:

输入:s = "0.9(9)", t = "1."
输出:true
解释:"0.9(9)" 代表 0.999999999... 永远重复,等于 1 。[有关说明,请参阅此链接]
"1." 表示数字 1,其格式正确:(IntegerPart) = "1" 且 (NonRepeatingPart) = "" 。

 

提示:

  • 每个部分仅由数字组成。
  • 整数部分 <IntegerPart> 不会以零开头。(零本身除外)
  • 1 <= <IntegerPart>.length <= 4
  • 0 <= <NonRepeatingPart>.length <= 4
  • 1 <= <RepeatingPart>.length <= 4
​​​​​
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间O(1)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate correctly identifies how to handle repeating decimal parts.

  • question_mark

    The candidate ensures that both numbers are normalized before comparison.

  • question_mark

    The candidate efficiently handles edge cases like 0.9(9) vs. 1.0.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle the infinite nature of repeating decimals, leading to inaccurate comparisons.

  • error

    Not normalizing the numbers correctly, which can result in a false conclusion of inequality.

  • error

    Overcomplicating the problem by focusing too much on string manipulations without recognizing the underlying mathematical nature.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handling more than two numbers and determining if all are equivalent.

  • arrow_right_alt

    Modifying the problem to compare fractions with non-repeating decimals.

  • arrow_right_alt

    Generalizing the solution to handle arbitrary precision numbers with repeating decimals.

help

常见问题

外企场景

相等的有理数题解:数学·string | LeetCode #972 困难