LeetCode --- 821. Shortest Distance to a Character 解题报告

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

 

Note:

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.

所有代码均可在Github中找到:

下载链接

# -*- coding:utf-8 -*-
__author__ = 'yangxin_ryan'
"""
Solutions:
题目的含义就是给定S,和其中的元素C,然后给出每个S中的元素距离C的最近距离;
一般遇到这种问题我们可以使用两侧依次遍历来解决。
例子:
S = "loveleetcode", C = 'e'
从左向右遍历,判断每个元素是否为C,是的话记录为0,不是的话利用下标记录距离,这里我们使用 (下标 - 无穷小 = 无穷大)的方式来标记第一次

你可能感兴趣的:(Python,算法,LeetCode,LeetCode,Python,算法)