一个含有字符串的数组,例如["a","b","a","c","b","d","a","1","1"]需要得到一个新数组 ["a1","b1","a2","c","b2","d","a3","11","12"]
时间: 2023-09-02 18:08:43 浏览: 89
数组与字符串
以下是Python代码实现:
```python
def combine_strings(arr):
counts = {}
new_arr = []
for string in arr:
if string in counts:
counts[string] += 1
new_arr.append(string + str(counts[string]))
else:
counts[string] = 1
new_arr.append(string)
return new_arr
```
代码思路:
1. 创建一个空字典counts,用于记录每个字符串出现的次数。
2. 遍历原始数组中的每个字符串。
3. 如果当前字符串已经在counts字典中,则将其出现次数加1,并将其拼接成新字符串添加到新数组中。
4. 如果当前字符串不在counts字典中,则将其添加到counts字典中,并直接将其添加到新数组中。
5. 返回新数组。
例如,对于输入数组["a","b","a","c","b","d","a","1","1"],counts字典的值会变化如下:
| 字符串 | 出现次数 |
| ---- | ---- |
| a | 1 |
| b | 1 |
| c | 1 |
| d | 1 |
| 1 | 1 |
| a | 2 |
| 1 | 2 |
最终,新数组的值为["a1","b1","a2","c","b2","d","a3","11","12"]。
阅读全文