题目:

Lexicographical order is often known as alphabetical order when dealing with strings. A string is greater than another string if it comes later in a lexicographically sorted list.Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria: (1)It must be greater than the original word. (2)It must be the smallest word that meets the first condition.Complete the function biggerIsGreater below to create and return the new string meeting the criteria. If it is not possible, return no answer.

附上链接:Bigger is Greater

初步逻辑

这个逻辑很难用语言描述,直接把我的实现代码贴上来

def biggerIsGreater(s):
i = 1
j = i + 1
while j > len(w) or w[-j] >= w[-i]:
if j > len(w):
i += 1
j = i + 1
if j > len(w):
return 'no answer'
else:
j += 1
else:
l = list(s)
l.insert(-j, s[-i])
l.pop(-i)
s = ''.join(l)
s = ''.join((lambda x, y: x + y)(list(s[-j + 1:]), list(s[:-j + 1])))
return s

逻辑本身没有问题,但是运行下去会发现,有三个例子是超时的

优质逻辑

发现了这个问题后,我却找不到解决办法,因为以往的超时都是由多重循环嵌套引起的,可这次明明只有一层循环,依然发生了超时的现象

于是,借助网站万能的Discussion,发现了其他人的一个很简洁的代码,如下

def biggerIsGreater(s):
for i in range(len(s) - 1)[::-1]:
if s[i] < s[i + 1]:
for j in range(i + 1, len(s))[::-1]:
if s[i] < s[j]:
lis = list(s)
lis[i], lis[j] = lis[j], lis[i]
return "".join(lis[:i + 1] + lis[i + 1:][::-1])
return 'no answer'

可它明明是两层嵌套循环,为什么要比我的运行的快呢。。。

初步感觉是因为我else里面的列表、字符串的操作占用了大量的时间,可是具体原因还是不清楚,有清楚的大佬愿意给我解释一下吗

最新文章

  1. 1171. Lost in Space
  2. css与js后边有?v=20160101
  3. 安装数据库出现错误vc_red.msi找不到
  4. Atitit.java expression fsm 表达式分词fsm引擎
  5. 在 C++Builder 工程里调用 DLL 函数
  6. tomcat项目发布 更改小猫图标 及自定义错误404界面
  7. matrix_2015_1 138 - ZOJ Monthly, January 2015
  8. IOS 开发过程中的 消息通知 小红点
  9. LeetCode Linked List Cycle 单链表环
  10. JavaScript语言用10张图
  11. UILabel设置富文本格式显示
  12. EntityFramework.Extended.Update.Ambiguous column name
  13. 查不到opencv版本的问题
  14. MySQL:Your password has expired. To log in you must change it using a client that supports expired passwords
  15. C++的一些知识
  16. spring ApplicationContext中Bean的生命周期
  17. CodeBblock 常用快捷键 (最常用)
  18. springboot自定义http反馈状态码
  19. Win10新增功能快捷键大全
  20. Fisher&ndash;Yates shuffle 洗牌算法(zz)

热门文章

  1. 嵌入式C语言4.2 C语言内存空间的使用-指针与修饰符:const,volatile,typedef
  2. python作业/练习/实战:生成双色球小程序
  3. swiper内容滚动太长滚动Bug
  4. 一道简单的面试题,难倒各大 Java 高手!
  5. Spring学习笔记(5)——IoC再度学习
  6. postgresql like 中的转义
  7. Linux (ifconfig/docker) 移除网桥/虚拟网卡
  8. jQuery实现点击按钮展开和收起
  9. mongoose 常用数据库操作 查询
  10. HIVE的Shell操作