中使用数据结构来解决这个问题,我们有4个字符(A,B,C和D)的序列,映射到数字形式1到n。 我们定义组件为:在O(n)
Component(k) :
A {cell[k]}
if Color(left_k) = Color(k)
then
A <-- A U Component(left_k)
if Color(right_k) = Color(k)
then
A <-- A U Component(left_k)
return A
有3种类型的操作(在列表中的数字表示输入):
通过给索引应该删除的组件在索引(映射到字符的数字是固定的)
例如:AABBBDA是字符串。如果索引是3应该通过给予指数应该旋转基于该索引组件上的串(数字映射到字符被固定)
例如返回AADA
:AABBBDA是字符串。如果索引是3,它应该返回DABBBAA
它应该打印字符串。
输入是这样的:
1 2 --> first operation with index=2
2 3 --> second operation with index=3
3 --> third operation
这是一个任务,高兴地得到帮助。
这是我试过到目前为止:
public static void main(String[] args)
{
int numberOfOps;
String[] print = new String[30];
List list = new List();
Scanner input = new Scanner(System.in);
int count = input.nextInt();
String colors = new String();
colors = input.next();
for(int i = 0; i < count; i++)
{
list.add(colors.charAt(i));
}
numberOfOps = input.nextInt();
list.printElement();
for (int i = 0; i < numberOfOps; i++)
{
int op = input.nextInt();
if(op == 1)
{
int index = input.nextInt();
char c = list.item[index];
int temp = index;
int prevIndex = index;
int nexIndex = index;
if(index != 0)
{
while (list.item[--index] == c)
{
prevIndex--;
}
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex-1, nexIndex+1);
}
else
{
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex, nexIndex+1);
}
}
if(op == 2)
{
int index = input.nextInt();
}
if(op == 3)
{
print[i] = list.printElement();
}
}
}
这里是我的表类:
public class List {
// reference to linked list of items
public static final int MAX_LIST = 20;
public static final int NULL = -1;
public char item[] = new char[MAX_LIST]; // data
public int avail;
public int next[] = new int[MAX_LIST]; // pointer to next item
private int numItems; // number of items in list
public List()
{
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
avail = 0;
} // end default constructor
public void add(char e)
{
item[avail] = e;
avail = next[avail];
numItems++;
}
public String printElement()
{
String temp = null;
int index = 0;
while(index<avail)
{
temp += item[index];
System.out.println(item[index]);
index = next[index];
}
return temp;
}
public int size()
{
return numItems;
}
public void setNext(int i, int value)
{
next[i] = value;
}
}
如果你测试它,你会得到的,它有很多的问题,例如,我不知道做旋转操作,并且在中间组件被移除时连接两个组件有问题。
我想用链表。 – Branky
如果我理解正确,如果顺序使用相同的字母,那么这个序列就被看作是一个“大”分量(在你的例子中,BBB和AA总是一起使用)?索引从1开始? (第一个字母在索引1)? – libik
@libik是的,这是正确的。索引是从1 – Branky