An in-place algorithm for String Transformation

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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;
}


内容概要:本文档定义了一个名为 `xxx_SCustSuplier_info` 的视图,用于整合和展示客户(Customer)和供应商(Supplier)的相关信息。视图通过连接多个表来获取组织单位、客户账户、站点使用、位置、财务代码组合等数据。对于客户部分,视图选择了与账单相关的记录,并提取了账单客户ID、账单站点ID、客户名称、账户名称、站点代码、状态、付款条款等信息;对于供应商部分,视图选择了有效的供应商及其站点信息,包括供应商ID、供应商名称、供应商编号、状态、付款条款、财务代码组合等。视图还通过外连接确保即使某些字段为空也能显示相关信息。 适合人群:熟悉Oracle ERP系统,尤其是应付账款(AP)和应收账款(AR)模块的数据库管理员或开发人员;需要查询和管理客户及供应商信息的业务分析师。 使用场景及目标:① 数据库管理员可以通过此视图快速查询客户和供应商的基本信息,包括账单信息、财务代码组合等;② 开发人员可以利用此视图进行报表开发或数据迁移;③ 业务分析师可以使用此视图进行数据分析,如信用评估、付款周期分析等。 阅读建议:由于该视图涉及多个表的复杂连接,建议读者先熟悉各个表的结构和关系,特别是 `hz_parties`、`hz_cust_accounts`、`ap_suppliers` 等核心表。此外,注意视图中使用的外连接(如 `gl_code_combinations_kfv` 表的连接),这可能会影响查询结果的完整性。
# DBSCAN from sklearn.cluster import DBSCAN import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt train_data = pd.read_csv('train.csv') test_data = pd.read_csv('test.csv') features = ['Annual Income', 'Years in current job', 'Tax Liens', 'Number of Open Accounts', 'Maximum Open Credit', 'Number of Credit Problems', 'Bankruptcies', 'Current Loan Amount', 'Current Credit Balance', 'Monthly Debt', 'Credit Score'] train_data[features] = train_data[features].fillna(train_data[features].mean()) test_data[features] = test_data[features].fillna(test_data[features].mean()) # 标准化 scaler = StandardScaler() train_scaled = scaler.fit_transform(train_data[features]) test_scaled = scaler.transform(test_data[features]) # DBSCAN聚类 dbscan = DBSCAN(eps=0.5, min_samples=5) dbscan.fit(train_scaled) # 将DBSCAN的聚类结果添加到DataFrame中 train_data['DBSCAN_Cluster'] = dbscan.labels_ # Agglomerative Clustering agg = AgglomerativeClustering(n_clusters=3) agg.fit(train_scaled) # 将Agglomerative Clustering的聚类结果添加到DataFrame中 train_data['Agglomerative_Cluster'] = agg.labels_ # Gaussian Mixture Model gmm = GaussianMixture(n_components=3) gmm.fit(train_scaled) # 将Gaussian Mixture Model的聚类结果添加到DataFrame中 train_data['GMM_Cluster'] = gmm.predict(train_scaled) # 可视化 plt.figure(figsize=(18, 6)) # DBSCAN聚类结果 plt.subplot(131) plt.scatter(train_data['Credit Score'], train_data['Annual Inc'], c=train_data['DBSCAN_Cluster'], cmap='viridis') plt.xlabel('Credit Score') plt.ylabel('Annual Income') plt.title('DBSCAN Clustering Results') # Agglomerative Clustering结果 plt.subplot(132) plt.scatter(train_data['Credit Score'], train_data['Annual Inc'], c=train_data['Agglomerative_Cluster'], cmap='viridis') plt.xlabel('Credit Score') plt.ylabel('Annual Income') plt.title('Agglomerative Clustering Results') # Gaussian Mixture Model结果 plt.subplot(133) plt.scatter(train_data['Credit Score'], train_data['Annual Inc'], c=train_data['GMM_Cluster'], cmap='viridis') plt.xlabel('Credit Score') plt.ylabel('Annual Income') plt.title('Gaussian Mixture Model Results') plt.tight_layout() plt.show()ValueError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_47176\2994685919.py in ?() ---> 17 # DBSCAN 18 from sklearn.cluster import DBSCAN 19 import pandas as pd 20 from sklearn.preprocessing import StandardScaler e:\Anaconda-python\envs\is6423new\lib\site-packages\sklearn\utils\_set_output.py in ?(self, X, *args, **kwargs) 138 @wraps(f) 139 def wrapped(self, X, *args, **kwargs): --> 140 data_to_wrap = f(self, X, *args, **kwargs) 141 if isinstance(data_to_wrap, tuple): 142 # only wrap the first output for cross decomposition 143 return_tuple = ( e:\Anaconda-python\envs\is6423new\lib\site-packages\sklearn\base.py in ?(self, X, y, **fit_params) 911 # non-optimized default implementation; override when a better 912 # method is possible for a given clustering algorithm 913 if y is None: 914 # fit method of arity 1 (unsupervised transformation) --> 915 return self.fit(X, **fit_params).transform(X) 916 else: 917 # fit method of arity 2 (supervised transformation) 918 return self.fit(X, y, **fit_params).transform(X) ... e:\Anaconda-python\envs\is6423new\lib\site-packages\pandas\core\generic.py in ?(self, dtype) 2069 def __array__(self, dtype: npt.DTypeLike | None = None) -> np.ndarray: -> 2070 return np.asarray(self._values, dtype=dtype) ValueError: could not convert string to float: '10+ years' 怎么改
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值