Python程序检查是否可以到达最左边或最右边位置


假设我们有一个字符串,包含三种类型的字符:R、B 和点(.)。其中 R 代表我们当前的位置,B 代表被阻挡的位置,点(.) 代表空闲位置。现在,我们可以在一步内移动到当前位置的任何相邻位置,只要该位置有效(空闲)。我们需要检查我们是否可以到达最左边或最右边的位置。

例如,如果输入是 s = "...........R.....BBBB.....",则输出为 True,因为 R 可以到达最左边位置,因为没有阻挡。

为了解决这个问题,我们将遵循以下步骤:

  • r_pos := s 中 'R' 的索引
  • 当 s[从索引 0 到 r_pos-1] 中不存在 'B' 或 s[从索引 r_pos 到结尾] 中不存在 'B' 时,返回 True

让我们看看下面的实现,以便更好地理解:

示例

 在线演示

class Solution:
   def solve(self, s):
      r_pos = s.find('R')
   return not 'B' in s[:r_pos] or not 'B' in s[r_pos:]
ob = Solution()
s = "...........R.....BBBB....."
print(ob.solve(s))

输入

"...........R.....BBBB....."

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

True

更新于: 2020年10月7日

308 次浏览

开启你的 职业生涯

完成课程获得认证

开始学习
广告