最近在准备南大软工的复试,正好把自己做的上机真题的解贴出来,希望可以帮助到对这道题有疑惑的同学。因为给自己限制了时间,所有没有做优化,望见谅。
题目:给一个字符串 由RGB(红绿蓝)3种字母组成
1.找出串中最长的相同子串,输出字母以及所在位置,然后剔除(如有多个相同拿最左的子串)
2.将剩余部分按序连接,如果只有一个字母则结束游戏,否则返回第一步
注意每次输出的位置为原始串中的位置
例:
RBBGGR
B 2 3
G 4 5
R 1 6
下面直接上代码。
public class Solution {
public void RGB(String S)
{
if(S.isEmpty())return ;
int [][]pos=new int [3][S.length()];//用三行来存储三个字母在预案字符串中出现的位置
char []arr=S.toCharArray();
int length=S.length();
int p1=0,p2=0,p3=0;
HashMap<Character,Integer> map=new HashMap<>();//定义一个map配合pos,value为对应行数。
map.put('R',0);
map.put('G',1);
map.put('B', 2);
for(int i=0;i<length;i++)
{
if(arr[i]=='R')
pos[0][p1++]=i+1;
if(arr[i]=='G')
pos[1][p2++]=i+1;
if(arr[i]=='B')
pos[2][p3++]=i+1;
}
while(length>0)
{
int start=0,end=0;//start为当前临时最长串的起点,end为当前轮最长串的终点
int maxs=0;//每轮最长串的起点
int max=1;//记录每轮的最大值
for(int i=0;i<length-1;i++)
{
int count=1;
if(arr[i]==arr[i+1])
{
start=i;
while(i+1<length&&arr[i]==arr[i+1])
{
count++;
i++;
}
if(count>max)
{
max=count;
end=i;
maxs=start;
}
}
}
System.out.print(arr[maxs]+" ");
int p=0;
int x=map.get(arr[maxs]);
while(pos[x][p]!=0)//输出原始串中对应字符的位置
{
System.out.print(pos[x][p]+" ");
p++;
}
System.out.println();
for(p=maxs;p+end-maxs+1<length;p++)//将数组前移
{
arr[p]=arr[p+end-maxs+1];
}
length=length-(end-maxs+1);
}
}
}
本文分享了南京大学软件工程硕士研究生复试的一道上机真题,涉及寻找RGB字符串中最长相同子串的问题。作者提供了个人解答,并指出代码未做优化。具体题目要求找到最长重复子串并删除,然后重组字符串,直至只剩一个字母。

327

被折叠的 条评论
为什么被折叠?



