在java中跟踪字符串中的字符

时间:2014-09-19 07:21:00

标签: java algorithm data-structures

假设我有一个字符串作为aabc。现在必须以循环方式将字符串中的字符移动为

aabc--->abca-->bcaa-->caab

现在我们看到第一个角色a被移动到第二个位置。 问题是字符串可以无限旋转。时间,但我必须跟踪第一个字符。 有没有办法做到这一点

3 个答案:

答案 0 :(得分:3)

  

问题是字符串可以无限旋转。时间,但我必须跟踪第一个字符。有没有办法做到这一点。

一般来说,没有。

考虑字符串"XXXX"。没有办法区分这个字符串可能的旋转。因此,您无法跟踪"原始字符串的第一个字符的位置。

另外,请考虑此字符串"abcd"。通过旋转弦可以达到4种可能的状态,但是有无限次的旋转。你可以"跟踪"第一个字符('a')......通过调用str.indexOf("a") ...但这并不能告诉你执行了多少轮换。 ('a'的最终位置告诉你总旋转模数字符串的长度。但它不能告诉你总旋转或单个旋转的顺序。)

答案 1 :(得分:1)

您可以使用简单的模数运算来实现它

代码:

int headPosition(int numberOfRotate, String val){
   numberOfRotate %= val.length();
   int pos = (val.length() - numberOfRotate)% val.length();       
   return pos;
}

函数headPosition将在numberOfRotate旋转后返回字符串的第一个字符。

注意:在不知道轮换次数的情况下,我认为您无法解决此问题,例如,如果输入字符串为aaaa,那么我们就不能识别哪个是第一个字符。

答案 2 :(得分:0)

Without knowing the number of rotations,如果您将原始索引保存在单独的数组中并执行same shift to the indices array too,则可能会这样做。

x为输入字符串,arr为索引array

int[] arr = new int[x.length()];

// fill the array with the indices.
for (int i=0;i<x.length();i++)
{
    arr[i] = i;
}
// for every move towards right, shift the elements in the array once towards right
int last = arr[arr.length-1];
System.arraycopy(arr, 0, arr, 1, arr.length-1 );
arr[0] = last;

// for every move towards left, shift the elements in the array once towards left
int first = arr[0];
System.arraycopy(arr, 1, arr, 0, arr.length-1 );
arr[arr.length-1 ] = first;


// Once all the iterations are done, the indices array will hold the original position
// of the elements in tact.

for (int i=0;i<arr.length;i++)
{
    System.out.println("original index is: "+ arr[i]+" of "+ x.charAt(arr[i]));
}