【每日一题0811】字符串递增器

:woman_mage:我们的任务是编写一个python函数,该函数接收一个字符串,以创建并返回一个新字符串。规则是:(1)如果输入字符串已经以一个数字结束,则该数字应该增加1;(2)如果输入字符串没有以数字结尾,那么数字1应该附加到新字符串中。

示例:
输入:hogwarts665 ,输出:hogwarts666
输入:hogwarts ,输出:hogwarts1

题目难度:简单
题目来源:codewars

def increment_string(s:str) -> str:
    pass
  
assert increment_string("hogwarts665") == "hogwarts666"
assert increment_string("hogwarts") == "hogwarts1"
assert increment_string("") == "1"
assert increment_string("hogwarts999") == "hogwarts1000"
assert increment_string("hogwarts001") == "hogwarts002"
```
def increment_str(test_str):
    if len(test_str) == 0:
        return "1"
    increase, res = 0, ""
    if test_str[-1].isdigit():
        increase = int(test_str[-1])
        res = test_str[0:-1]
    else:
        res = test_str
    increase += 1
    return res + str(increase)
def increment_string(s:str)->str:
    if len(s)==0:
        return '1'
    end=s[-1]
    li2=['0','1','2','3','4','5','6','7','8','9']
    y=''
    num=0
    if end.isdigit() is False:
        return s+'1'
    for i in range(len(s)):
        if s[-(i+1)] in li2:
            y=s[-(i+1)]+y
        else:
            num=i
            break
    return s[:(-num)] + str(int(y) + 1)

如果尾数为999的话好像不对哦

def increment_string(s: str) -> str:
    if re.findall(r"\d+$", s):
        return re.sub(r"\d+$", str(int(re.findall(r"\d+$", s)[0]) + 1), s, 1)
    else:
        return s + "1"


assert increment_string("hogwarts665") == "hogwarts666"
assert increment_string("hogwarts") == "hogwarts1"
assert increment_string("") == "1"

image

import re
def increment_string(s: str) -> str:

    return re.sub("[\d+]", "", s)+ str(int(re.sub("[^\d\+]", "", s)) + 1)  if bool(re.search('\d', s)) else s + '1'

assert increment_string("hogwarts665") == "hogwarts666"
assert increment_string("foo099") == "foo100"
assert increment_string("hogwarts") == "hogwarts1"
assert increment_string("") == "1"
import re
from decimal import Decimal

def increment_string(s: str) -> str:
    number = re.findall(r"\d+\.?\d*", s)
    res = ""
    if not number or len(s) == 0:
        res = s + "1"
    elif s.endswith(number[-1]) and not s.endswith('.'):
        number[-1] = '{:g}'.format(Decimal(number[-1]))
        sa = str(number[-1])
        index = sa.find('.')
        ws = 0
        if index < 0:
            tempdata = int(number[-1]) + 1
        else:
            ws = len(sa[index + 1:len(sa)])
            tempdata = Decimal(number[-1]) + Decimal(1 / pow(10, ws))
        res = s[0:len(s) - len(number[-1])] + '{:g}'.format(round(Decimal(tempdata), ws))
    else:
        res = s + "1"
    print(res)
    return res
def increment_string(s:str) -> str:
    cursor = 0
    for i in range(len(s)):
        if not s[len(s)-i-1].isdigit():
            cursor = len(s)-i-1
            break
    head = s[:cursor + 1]
    tail = s[cursor + 1:]
    
    tail_plus_one = f'%0{len(tail)}d' % (int(tail if tail else 0)+1)
    
    return f'{head}{tail_plus_one}'

assert increment_string("hogwarts665") == "hogwarts666"
assert increment_string("hogwarts") == "hogwarts1"
assert increment_string("") == "1"
assert increment_string("hogwarts999") == "hogwarts1000"
assert increment_string("hogwarts001") == "hogwarts002"

解题思路:首先,从右侧开始找,找到数字和非数字的分界线,也就是倒着找首次出现的字母/字符的下标。然后对尾部纯数字部分进行加1计算。这里有2个场景需要注意:(1)是纯数字可能是xxx001这种格式,返回的字符串中需要保留中间的0;(2)是需要考虑进位的场景,例如xxx9999尾部数字刚好是3位999,加1后需要返回4位字符的xxx1000

备注:对于处理001转成数字并加1后格式化返回002,可以考虑使用%占位符来实现。'%06d' % n 表示最小宽度为6,位数不够则自动补位0占位,例如'%06d' % 1将得到000001