017/learn
/learn/01.基础语法与数据结构/01.字符串/07.字符替换.py
# 题目描述
输入一个字符串,将字符串中的每个空格替换成“%20”。例如输入“We Are Happy”,则输出“We%20Are%20Happy”。
# 思路
- 遍历字符串,遇到空格就将空格替换为“%20”,遇到其他字符就继续向后遍历。
# 代码
```python
class Solution:
def replaceSpace(self, s):
# write code here
i = 0
while i < len(s):
if s[i] == ' ':
s = s[:i] + '%20' + s[i+1:]
i += 1
return s
```
/learn/01.基础语法与数据结构/07.列表/15.列表遍历.py
# 题目描述
输入一个整数,输出该整数二进制表示中1的个数。其中整数正负不限。
# 思路
- 二进制表示中1的个数,可以将该整数不断除以2,余数为1则计数加1。直到该整数为0为止。
# 代码
```python
class Solution:
def NumberOf1(self, n):
# write code here
count = 0
while n:
count += 1
n &= (n - 1)
return count
```
/learn/01.基础语法与数据结构/01.字���串/06.字符串翻转.py
# 题目描述
输入一个链表,输出该链表中倒数第k个结点。
# 思路
- 首先找到链表的长度,然后通过长度减去k,就可以得到倒数第k个结点的正序编号,再从头开始遍历链表,找到正序编号为k的结点,即为所求。
# 代码
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k < 1:
return
cur = head
num = 0
while cur:
cur = cur.next
num += 1
k = num - k
while k:
head = head.next
k -= 1
return head.val
```
/learn/01.基础语法与数据结构/02.列表与集合/06.列表的切片.py
# 题目描述
输入一个字符串,求该字符串中字符出现的次数,返回一个字典,键为字符,值为字符出现的次数。
# 思路
- 遍历字符串,记录字符出现的次数,最后返回字典。
# 代码
```python
class Solution:
def NumberOf1(self, n):
# write code here
count = 0
while n:
n &= (n - 1)
count += 1
return count
```
/learn/01.基础语法与数据结构/01.字符串/04.字符串反转.py
# 题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
# 思路
- 递归求解。将字符串分为头尾两部分,先打印尾部字符,再遍历头部字符,将头部字符插入尾部字符的每一种排列中。递归终止条件是头部字符串为空,或者尾部字符串为空。
# 代码
```python
class Solution:
def Permutation(self, ss):
# write code here
if not ss or len(ss) < 1:
return []
if len(ss) == 1:
return [ss]
res = []
for i in range(len(ss)):
for item in self.Permutation(ss[:i] + ss[i+1:]):
res.append(ss[i] + item)
return res
```
/learn/01.基础语法与数据结构/03.函数/10.求阶乘.py
# 题目描述
输入一个字符串,将其反转后输出。
# 思路
- 反转字符串,可以将字符串按字符存储到列表中,然后从列表的最后一位开始,依次取出列表中的元素,将其插入到新的字符串中,即完成了字符串的反转。
# 代码
```python
class Solution:
def reverseString(self, s):
# write code here
if not s:
return
s = list(s)
result = ''
for i in range(len(s)):
result += s.pop()
return result
```
/learn/01.基础语法与数据结构/01.字符串/03.字符串转列表.py
# 题目描述
输入一个整数,输出该整数二进制表示中1的个数。其中正负整数正负不限。
# 思路
- 二进制表示中1的个数,可以将该整数不断除以2,余数为1则计数加1。直到该整数为0为止。
# 代码
```python
class