Alphabet wars - nuclear strike–5 kyu–Python解法


Codewars 是一个跟LeetCode类似的结题网站。
Codewars题解专栏:Codewars题解


题目地址:Kata Stats: Alphabet wars - nuclear strike | Codewars


Introduction

There is a war and nobody knows - the alphabet war!
The letters hide in their nuclear shelters. The nuclear strikes hit the battlefield and killed a lot of them.

Task
Write a function that accepts battlefield string and returns letters that survived the nuclear strike.

The battlefield string consists of only small letters, #,[ and ].
The nuclear shelter is represented by square brackets []. The letters inside the square brackets represent letters inside the shelter.
The # means a place where nuclear strike hit the battlefield. If there is at least one # on the battlefield, all letters outside of shelter die. When there is no any # on the battlefield, all letters survive (but do not expect such scenario too often ;-P ).
The shelters have some durability. When 2 or more # hit close to the shelter, the shelter is destroyed and all letters inside evaporate. The ‘close to the shelter’ means on the ground between the shelter and the next shelter (or beginning/end of battlefield). The below samples make it clear for you.
Example

abde[fgh]ijk     => "abdefghijk"  (all letters survive because there is no # )
ab#de[fgh]ijk    => "fgh" (all letters outside die because there is a # )
ab#de[fgh]ij#k   => ""  (all letters dies, there are 2 # close to the shellter )
##abde[fgh]ijk   => ""  (all letters dies, there are 2 # close to the shellter )
##abde[fgh]ijk[mn]op => "mn" (letters from the second shelter survive, there is no # close)
#ab#de[fgh]ijk[mn]op => "mn" (letters from the second shelter survive, there is no # close)
#abde[fgh]i#jk[mn]op => "mn" (letters from the second shelter survive, there is only 1 # close)
[a]#[b]#[c]  => "ac"
[a]#b#[c][d] => "d"
[a][b][c]    => "abc"
##a[a]b[c]#  => "c"

这道题目是5 kyu难度的,说难不难,说简单,要花费一定的时间。

Python解法如下:

def alphabet_war(battlefield):if '#' not in battlefield:return battlefield.replace('[', '').replace(']', '')l = []for i in range(0, len(battlefield)):if battlefield[i] == '#':    l.append('#')elif battlefield[i] == '[':  begin = ielif battlefield[i] == ']':  l.append(battlefield[begin:i+1])for i in range(0, len(l)):if l[i] == '#':while i >= 0 and l[i] == '#': i -= 1if i >= 0:if l[i][-1] == '1':    l[i] = l[i][:-1]+'2'elif l[i][-1] == ']':  l[i] = l[i][:-1]+'1'      i = i+1while i < len(l) and l[i] == '#': i += 1if i < len(l):if l[i][0] == '1':    l[i] = '2'+l[i][1:]elif l[i][0] == '[':  l[i] = '1'+l[i][1:]res = ""for i in range(0, len(l)):if l[i] != '#'and l[i][0] != '2' and l[i][-1] != '2' \and not (l[i][0] == '1'and l[i][-1] == '1'):res = res+l[i][1:-1]return res

从我的解法中可以看出有一定的冗余存在。
看了别人的解法,有很多人都用了正则表达式,但我感觉短时间内肯定想不出这种解法:

import re
def alphabet_war(b):if '#' not in b:return re.sub(r"[\[\]]","",b)p = re.compile('([a-z#]*)\[([a-z]+)\](?=([a-z#]*))')return  ''.join( e[1] if (e[0]+e[2]).count('#') < 2 else'' for e in p.findall(b))

Alphabet wars - nuclear strike--5 kyu--Python解法相关推荐

  1. LeetCode 111. Minimum Depth of Binary Tree--Java, Python解法--二叉树最小高度--迭代,递归

    题目地址:Minimum Depth of Binary Tree - LeetCode Given a binary tree, find its minimum depth. The minimu ...

  2. LeetCode 226. Invert Binary Tree--反转二叉树--C++,Python解法--递归,迭代做法

    题目地址:Invert Binary Tree - LeetCode Invert a binary tree. Example: Input: 4/ \2 7/ \ / \ 1 3 6 9 Outp ...

  3. LeetCode 204. Count Primes--从一开始的质数个数--Python解法--面试算法题

    题目地址:Count Primes - LeetCode Count the number of prime numbers less than a non-negative number, n. E ...

  4. LeetCode 458. Poor Pigs--智力题「小白鼠试毒」--C++,Python解法

    题目地址:Poor Pigs - LeetCode There are 1000 buckets, one and only one of them is poisonous, while the r ...

  5. LeetCode 230. Kth Smallest Element in a BST--C++,Python解法--面试真题--找二叉树中第K小的元素

    题目地址:Kth Smallest Element in a BST - LeetCode Given a binary search tree, write a function kthSmalle ...

  6. LeetCode 221. Maximal Square----动态规划--谷歌面试算法题--Python解法

    题目地址:Maximal Square - LeetCode Given a 2D binary matrix filled with 0's and 1's, find the largest sq ...

  7. LeetCode 148. Sort List--面试算法题--C++,Python解法

    LeetCode 148. Sort List–面试算法题–C++,Python解法 LeetCode题解专栏:LeetCode题解 LeetCode 所有题目总结:LeetCode 所有题目总结 大 ...

  8. LeetCode 20. Valid Parentheses--笔试题--Python解法

    题目地址:Valid Parentheses - LeetCode Given a string containing just the characters '(', ')', '{', '}', ...

  9. LeetCode 145. Binary Tree Postorder Traversal--后序遍历--先序遍历反向输出--递归,迭代--C++,Python解法

    题目地址:Binary Tree Postorder Traversal - LeetCode Given a binary tree, return the postorder traversal ...

最新文章

  1. B.Sport Mafia
  2. 【转】一位软件工程师的6年总结
  3. Java 里的字符串处理类StringBuffer简介
  4. SAP 动态设置 GUI STATUS 灰色不可用 或者隐藏
  5. 入门视频采集与处理(BT656简介) 转
  6. Linux用户空间将虚拟地址转化为物理地址
  7. Net窗体程序设计总结
  8. opencv基础:adaboost+haar目标检测技术(上)
  9. Python-GDAL读取遥感影像直方图统计
  10. myeclipse 扩展内存大小
  11. Delphi7 SqlServer实现数据的CRUD(一)
  12. 直播纠纷处理指引已出台,电商直播严监管来了!
  13. 照片宽高比怎么设置_2019年中级会计报名照片上传完整攻略
  14. 错误 LNK2005 xxx已经在 xxx.obj 中定义
  15. 初识人工智能,机器学习,深度学习的关系(概念)
  16. 聚类分析通俗易懂解释
  17. Steinitz exchange lemma
  18. 何恺明一作论文 MAE 已有人复现!PyTorch 版!
  19. 英语差python好学吗,英语不好可以学习编程嘛?
  20. 全局钩子(hook鼠标键盘消息)

热门文章

  1. Chemistry.AI | 基于循环神经网络(RNN)预测分子性质
  2. RDKit | 分子处理入门
  3. 第二十一课.粒子滤波器
  4. go 二进制程序守护_GO-环境设置
  5. 在线作图|两分钟在线做中性群落模型分析
  6. Soil Ecology Letters被ESCI收录
  7. ​纳米孔测序揭示冻土冻融对土壤微生物群落变化的影响
  8. ggplot2笔记7:定位(分面和坐标系)
  9. 宏基因组教程Metagenomics Tutorial (HUMAnN2)
  10. java 异常类_Java异常处理