waker0086 / HW-NKcode

https://www.nowcoder.com/exam/oj?page=1&pageSize=50&search=&tab=%E5%90%8D%E4%BC%81%E7%9C%9F%E9%A2%98&topicId=37
0 stars 0 forks source link

HJ1-字符串最后一个单词的长度 #简单#字符串 #1

Open waker0086 opened 2 years ago

waker0086 commented 2 years ago

描述 计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾) 输入描述: 输入一行,代表要计算的字符串,非空,长度小于5000。

输出描述: 输出一个整数,表示输入字符串最后一个单词的长度。

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

waker0086 commented 2 years ago

方法一:使用内置函数

使用python中字符串的内置函数strip()去除字符串首尾空格,使用split()按照空格将字符串切分成单词数组,找到最后一个单词并计算其长度

使用strip()去除首尾空格 使用split()将字符串切分成单词数组 计算数组最后一个单词长度

image

时间复杂度分析: O(n)

空间复杂度分析: O(n)

def last_word_length(input()):
    word_list = input().strip().split()
    l = len(word_list[-1])
    return l

方法二 指针从数组尾部向数组头部移动,判断并计算移动距离

去除字符串首尾空格,设置指针,从数组的末尾向数组头部移动,直至遇到空格或者遇到数组首位元素,此时指针移动距离即最后一个单词的长度

去掉首尾空格 指针从数组末尾开始移动,判断

image

def last_word_length(input()):
  input_str = input().strip()
  dis = 0
  for i in range(len(input_str)-1, -1, -1):  #从最后一个循环到第一个
    if input_str[i] == ' ':
      break
    dis += 1
  print(dis)

# def last_word_length(word):
#     n = len(word)
#     l = 0
#     for i in range(-1, -n - 1, -1):  #从最后一个循环到第一个
#         if word[i] == ' ' and i > -n:
#             break
#         l += 1
#     return l
waker0086 commented 2 years ago

python 循环退出与跳过

错误循环

# def last_word_length(word):
#     n=len(word)
#     for i in range(-1,-n-1,-1):
#         if word[i] == ' ':
#             break
#     return abs(i)-1

此时不满足只有一个单词情况,即字符串中不存在空格,刚好遍历完整个字符串

不应该用i作为标准来计算长度,而是计算循环的次数,此处对于满足空格的轮次,直接退出整个循环,而不用计算 +1

break 和 continue 语句及循环中的 else 子句

https://www.runoob.com/python3/python3-loop.html

image

image

实例

while 中使用 break:

实例

n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('循环结束。')

输出结果为:

4 3 循环结束。

while 中使用 continue:

实例

n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束。')

输出结果为:

4 3 1 0 循环结束。

waker0086 commented 2 years ago

Python strip()方法

基本语法

str.strip([chars]);

str = "123abcrunoob321" print (str.strip( '12' )) # 字符序列为 12


输出

`3abcrunoob3`
waker0086 commented 2 years ago

Python split()方法

https://www.runoob.com/python/att-string-split.html

基本语法

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串 str.split(str="", num=string.count(str)).

参数

  1. 实例1
#!/usr/bin/python
# -*- coding: UTF-8 -*-

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );       # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

  1. 实例2 以下实例以 # 号为分割符,指定第二个参数为 1,返回两个参数列表。
    
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-

txt = "Google#Runoob#Taobao#Facebook"

第二个参数为 1,返回两个参数列表

x = txt.split("#", 1)

print x



> ['Google', 'Runoob#Taobao#Facebook']  **#并不包括分隔符本身**