An in-place algorithm for String Transformation

本文介绍了一种高效的字符串处理算法,该算法能在O(n)的时间复杂度内将字符串中的偶数位置字符移动到字符串末尾,同时保持字符的相对顺序不变。通过详细步骤分解和示例说明,读者可以了解如何实现这一算法。

不好意思,我没有进行翻译,觉得原文讲的很好:

Given a string, move all even positioned elements to end of string. While moving elements, keep the relative order of all even positioned and odd positioned elements same. For example, if the given string is “a1b2c3d4e5f6g7h8i9j1k2l3m4″, convert it to “abcdefghijklm1234567891234″ in-place and in O(n) time complexity.
Below are the steps:
1. Cut out the largest prefix sub-string of size of the form 3^k + 1. In this step, we find the largest non-negative integer k such that 3^k+1 is smaller than or equal to n (length of string)
2. Apply cycle leader iteration algorithm ( it has been discussed below ), starting with index 1, 3, 9…… to this sub-string. Cycle leader iteration algorithm moves all the items of this sub-string to their correct positions, i.e. all the alphabets are shifted to the left half of the sub-string and all the digits are shifted to the right half of this sub-string.
3. Process the remaining sub-string recursively using steps#1 and #2.
4. Now, we only need to join the processed sub-strings together. Start from any end ( say from left ), pick two sub-strings and apply the below steps:
….4.1 Reverse the second half of first sub-string.
….4.2 Reverse the first half of second sub-string.
….4.3 Reverse the second half of first sub-string and first half of second sub-string together.
5. Repeat step#4 until all sub-strings are joined. It is similar to k-way merging where first sub-string is joined with second. The resultant is merged with third and so on.
Let us understand it with an example:
Please note that we have used values like 10, 11 12 in the below example. Consider these values as single characters only. These values are used for better readability.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
a 1 b 2 c 3 d 4 e 5 f  6  g  7  h  8  i  9  j  10 k  11 l  12 m  13
After breaking into size of the form 3^k + 1, two sub-strings are formed of size 10 each. The third sub-string is formed of size 4 and the fourth sub-string is formed of size 2.
0 1 2 3 4 5 6 7 8 9         
a 1 b 2 c 3 d 4 e 5      

10 11 12 13 14 15 16 17 18 19          
f  6  g  7  h  8  i  9  j  10           
20 21 22 23 
k  11 l  12 
24 25
m  13
After applying cycle leader iteration algorithm to first sub-string:
0 1 2 3 4 5 6 7 8 9          
a b c d e 1 2 3 4 5          
10 11 12 13 14 15 16 17 18 19          
f  6  g  7  h  8  i  9  j  10 
20 21 22 23 
k  11 l  12 
24 25
m  13
After applying cycle leader iteration algorithm to second sub-string:
0 1 2 3 4 5 6 7 8 9          
a b c d e 1 2 3 4 5          
10 11 12 13 14 15 16 17 18 19           
f  g  h  i  j  6  7  8  9  10 
20 21 22 23 
k  11 l  12 
24 25
m 13
After applying cycle leader iteration algorithm to third sub-string:
0 1 2 3 4 5 6 7 8 9          
a b c d e 1 2 3 4 5          
10 11 12 13 14 15 16 17 18 19            
f  g  h  i  j  6  7  8  9  10
20 21 22 23 
k  l  11 12 
24 25
m  13
After applying cycle leader iteration algorithm to fourth sub-string:
0 1 2 3 4 5 6 7 8 9  
a b c d e 1 2 3 4 5  
10 11 12 13 14 15 16 17 18 19             
f  g  h  i  j  6  7  8  9  10   
20 21 22 23 
k  l  11 12 
24 25
m  13
Joining first sub-string and second sub-string:
1. Second half of first sub-string and first half of second sub-string reversed.
0 1 2 3 4 5 6 7 8 9          
a b c d e 5 4 3 2 1            <--------- First Sub-string  
10 11 12 13 14 15 16 17 18 19             
j  i  h  g  f  6  7  8  9  10  <--------- Second Sub-string  
20 21 22 23 
k  l  11 12 
24 25
m  13
2. Second half of first sub-string and first half of second sub-string reversed together( They are merged, i.e. there are only three sub-strings now ).
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
a b c d e f g h i j 1  2  3  4  5  6  7  8  9  10
20 21 22 23 
k  l  11 12 
24 25
m  13
Joining first sub-string and second sub-string:
1. Second half of first sub-string and first half of second sub-string reversed.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
a b c d e f g h i j 10 9  8  7  6  5  4  3  2  1 <--------- First Sub-string  
20 21 22 23 
l  k  11 12                                      <--------- Second Sub-string
24 25
m  13
2. Second half of first sub-string and first half of second sub-string reversed together( They are merged, i.e. there are only two sub-strings now ).
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  
a b c d e f g h i j k  l  1  2  3  4  5  6  7  8  9  10 11 12  
24 25
m  13 
Joining first sub-string and second sub-string:
1. Second half of first sub-string and first half of second sub-string reversed.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 
a b c d e f g h i j k  l  12 11 10 9  8  7  6  5  4  3  2  1 <----- First Sub-string
24 25
m  13   <----- Second Sub-string 
2. Second half of first sub-string and first half of second sub-string reversed together( They are merged, i.e. there is only one sub-string now ).
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
a b c d e f g h i j k  l  m  1  2  3  4  5  6  7  8  9  10 11 12 13
Since all sub-strings have been joined together, we are done.
How does cycle leader iteration algorithm work?
Let us understand it with an example:
Input:
0 1 2 3 4 5 6 7 8 9
a 1 b 2 c 3 d 4 e 5
Output:
0 1 2 3 4 5 6 7 8 9 
a b c d e 1 2 3 4 5
Old index    New index
0 0
1 5
2 1
3 6
4 2
5 7
6 3
7 8
8 4
9 9
Let len be the length of the string. If we observe carefully, we find that the new index is given by below formula:
if( oldIndex is odd )
newIndex = len / 2 + oldIndex / 2;
else
        newIndex = oldIndex / 2;
So, the problem reduces to shifting the elements to new indexes based on the above formula.
Cycle leader iteration algorithm will be applied starting from the indices of the form 3^k, starting with k = 0.
Below are the steps:
1. Find new position for item at position i. Before putting this item at new position, keep the back-up of element at new position. Now, put the item at new position.
2. Repeat step#1 for new position until a cycle is completed, i.e. until the procedure comes back to the starting position.
3. Apply cycle leader iteration algorithm to the next index of the form 3^k. Repeat this step until 3^k < len.
Consider input array of size 28:
The first cycle leader iteration, starting with index 1:
1->14->7->17->22->11->19->23->25->26->13->20->10->5->16->8->4->2->1
The second cycle leader iteration, starting with index 3:
3->15->21->24->12->6->3
The third cycle leader iteration, starting with index 9:
9->18->9
Based on the above algorithm, below is the code:

#include<iostream>
#include<string>
#include<cmath>
using namespace std;

void swap(char &a, char &b) {
	b ^= a;
	a ^= b;
	b ^= a;
}

void reverse(char *s, int start, int end) {
	while (start < end) {
		swap(*(s + start), *(s + end));
		start++;
		end--;
	}
}

void cycleLeader(char *s, int offset, int len) {
	int i, index;
	char item;
	for (i = 1; i < len; i *= 3) {
		index = i;
		item = s[index + offset];
		do {
			if (index & 0x01)
				index = len / 2 + index / 2;
			else
				index = index / 2;
			swap(*(s + index + offset), item);
		} while (index != i);
	}
}

void inPlaceMove(char *s, int length) {
	int left_len = length;
	int part_len = 0;
	int k = 0;
	int offset = 0;
	while (left_len) {
		k = 0;
		while (pow((double)3, k) + 1 <= left_len)
			k++;
		part_len = pow((double)3, k - 1) + 1;
		left_len -= part_len;
		cycleLeader(s, offset, part_len);
		if (offset) {
			reverse(s, offset / 2, offset - 1);
			reverse(s, offset, offset + part_len / 2 - 1);
			reverse(s, offset / 2, offset + part_len / 2 - 1);
		}
		offset += part_len;
	}
}

int main(int argc, char *argv[]) {
	char s[] = "1a2b3c4d5e6f7g8h9i";
	int n = strlen(s);
	inPlaceMove(s, n);
	cout << s << endl;
	cin.get();
	return 0;
}


(1)普通用户端(全平台) 音乐播放核心体验: 个性化首页:基于 “听歌历史 + 收藏偏好” 展示 “推荐歌单(每日 30 首)、新歌速递、相似曲风推荐”,支持按 “场景(通勤 / 学习 / 运动)” 切换推荐维度。 播放页功能:支持 “无损音质切换、倍速播放(0.5x-2.0x)、定时关闭、歌词逐句滚动”,提供 “沉浸式全屏模式”(隐藏冗余控件,突出歌词与专辑封面)。 多端同步:自动同步 “播放进度、收藏列表、歌单” 至所有登录设备(如手机暂停后,电脑端打开可继续播放)。 音乐发现与管理: 智能搜索:支持 “歌曲名 / 歌手 / 歌词片段” 搜索,提供 “模糊匹配(如输入‘晴天’联想‘周杰伦 - 晴天’)、热门搜索词推荐”,结果按 “热度 / 匹配度” 排序。 歌单管理:创建 “公开 / 私有 / 加密” 歌单,支持 “批量添加歌曲、拖拽排序、一键分享到社交平台”,系统自动生成 “歌单封面(基于歌曲风格配色)”。 音乐分类浏览:按 “曲风(流行 / 摇滚 / 古典)、语言(国语 / 英语 / 日语)、年代(80 后经典 / 2023 新歌)” 分层浏览,每个分类页展示 “TOP50 榜单”。 社交互动功能: 动态广场:查看 “关注的用户 / 音乐人发布的动态(如‘分享新歌感受’)、好友正在听的歌曲”,支持 “点赞 / 评论 / 转发”,可直接点击动态中的歌曲播放。 听歌排行:个人页展示 “本周听歌 TOP10、累计听歌时长”,平台定期生成 “全球 / 好友榜”(如 “好友中你本周听歌时长排名第 3”)。 音乐圈:加入 “特定曲风圈子(如‘古典音乐爱好者’)”,参与 “话题讨论(如‘你心中最经典的钢琴曲’)、线上歌单共创”。 (2)音乐人端(创作者中心) 作品管理: 音乐上传:支持 “无损音频(FLAC/WAV)+ 歌词文件(LRC)+ 专辑封面” 上传,填写 “歌曲信息
### In-Place Algorithm Implementation and Usage In-place algorithms operate directly on input data structures without requiring additional memory allocation proportional to the size of the input. These algorithms modify elements within existing storage locations rather than creating new ones, which can lead to significant performance improvements by reducing space complexity. #### Characteristics of In-Place Algorithms An in-place operation modifies an object without producing a separate result object; instead, changes occur inside the original one. For instance, sorting operations like QuickSort or Merge Sort variants may implement this approach when working with arrays where swaps happen between indices belonging to the same array[^1]. When discussing refactorings as described elsewhere, transforming non-in-place methods into their counterparts could involve altering how temporary variables store intermediate results during computation phases while preserving overall functionality[^2]. #### Example: Implementing an In-Place Operation Using Python Consider reversing a list in place: ```python def reverse_in_place(lst): start_index = 0 end_index = len(lst)-1 while start_index < end_index: lst[start_index], lst[end_index] = lst[end_index], lst[start_index] start_index += 1 end_index -= 1 sample_list = ['a', 'b', 'c'] reverse_in_place(sample_list) print(sample_list) # Output will be ['c', 'b', 'a'] ``` This function reverses `lst` without allocating extra lists for storing reversed items temporarily. The swap happens internally through index manipulation alone. #### Applications Beyond Sorting and Reversal Beyond simple transformations such as reversal or ordering sequences numerically/alphabetically, other areas benefitting from in-place processing include matrix transposition, string manipulations, graph traversals optimized via adjacency matrices, etc.[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值