算法题题解记录——3. 数字字符串格式化

146 阅读1分钟

题目

www.marscode.cn/practice/r3…

image.png

过程

  1. 去除前导零;
  2. 查找小数点位置,记录l,r位置;
  3. l向左遍历,拼接整数部分,每隔3个数拼接逗号(,);
  4. r向右遍历,拼接小数部分。

代码

def solution(s: str) -> str:
    # write code here
    s = filter_leading_zeros(s)

    l = r = -1
    pIndex = s.find('.')
    if pIndex >= 0:
        r = pIndex + 1
        l = pIndex - 1
    else:
        l = len(s) - 1

    ans: str = ''

    for i in range(l, -1, -1):
        if l != i and (l - i) % 3 == 0:
            ans = ',' + ans
        ans = s[i] + ans

    if (r != -1):
        ans = ans + '.' + s[r:]

    return ans


def filter_leading_zeros(s: str) -> str:
    i = 0  # 第一个非0的位置
    while i < len(s):
        if s[i] == '0' or (s[i + 1] is not None and s[i + 1] == '.'):
            i += 1
        else:
            break

    return s[i:] if i < len(s) else '0'


if __name__ == '__main__':
    print(solution("1294512.12412") == '1,294,512.12412')
    print(solution("0000123456789.99") == '123,456,789.99')
    print(solution("987654321") == '987,654,321')

复杂度

  • 时间复杂度 O(n)
  • 空间复杂度 O(n)

学到了

  1. python的切片操作[start:end:step],[::-1]可以翻转字符串或数组,[i:] 是返回切取i之后(包括i)的元素(不改变原变量);
  2. for i in range(start, end, step): 遍历,从start遍历到end,包括start但不包括end,step可以控制方向(负数)和步长;
  3. s.find()找下标;
  4. is not None 判断非空;
  5. and 逻辑与运算 即js中的&&,or 逻辑或运算 即js中的||;
  6. return a if condition else b 如果 condition为真返回a否则返回b;
  7. python内置str的方法lstrip可以去除字符串开头所指定的字符(另外还有rstrip去除末尾指定字符、strip去除收尾指定字符),但毕竟是算法题,还是选择用最原始的方法。