第一种,简洁算法
根据矩阵运算中的可得
package com.liangyumingblog;
public class RollUpString
{
private String string;
public RollUpString(String s)
{
this.string = s;
}
public String rollup(int n)
{
StringBuilder s1 = new StringBuilder(string.substring(0, n));
StringBuilder s2 = new StringBuilder(string.substring(n + 1));
return s1.reverse().append(s2.reverse().toString()).reverse().toString();
}
}
可以不变动实际数组,我们滑动数组指针使得逻辑上看起来是左移了N位
package com.liangyumingblog;
public class RollUpStringCycleList
{
private char[] string;
private int begin;
public RollUpStringCycleList(String s)
{
this.string = s.toCharArray();
this.begin = 0;
this.end = s.length() - 1;
}
public void rollup(int n)
{
int localN = n;
while (localN >= string.length)
{
localN -= string.length;
}
begin += localN;
end = begin;
}
private int end;
public boolean hasNext()
{
return begin + 1 != end;
}
public Object next()
{
if (begin + 1 == string.length - 1)
{
begin = -1;
return string[string.length - 1];
}
return string[++begin];
}
}
两种不同的实现和使用方式
package com.liangyumingblog;
public class Test
{
public static void main(String[] s)
{
RollUpString rollUpString = new RollUpString("ABCDEFGHIJKF");
System.out.println(rollUpString.rollup(5));
RollUpStringCycleList rollUpStringCycleList = new RollUpStringCycleList("ABCDEFGHIJKF");
rollUpStringCycleList.rollup(5);
System.out.print(rollUpStringCycleList.next());
while (rollUpStringCycleList.hasNext())
{
System.out.print(rollUpStringCycleList.next());
}
}
}
GHIJKFABCDE
GHIJKFABCDE
Process finished with exit code 0