将字符串中的字符向左移动 [英] Shifting characters in a string to the left

查看:98
本文介绍了将字符串中的字符向左移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Stack Overflow的新手,我对一个一直在逃避我的编程课有一个实验室问题。问题要求我们将字符串s的元素向左移动k次。例如,如果输入是Hello World和3,则输出lo WorldHel)。对于非常大的k值,它还必须相对有效地工作。这就是我到目前为止:

I'm new to Stack Overflow and I have a lab question for a programming class that's been eluding me. The problem requires us to shift the elements of a string s to the left k times. For instance, if the input is "Hello World" and 3, it would output "lo WorldHel"). It also has to work relatively efficiently for very large values of k. This is what I have so far:

 String cyclicLeftShift(String s, int k){
   String result="";  

   for(int i=0;i<k;i++){
       result = s.substring(1, s.length() - 1) +s.charAt(0);

       s=result;
    }
    return s;
}

我的主要问题是原始字符串的最后一个字符一直被覆盖循环的后续迭代。我已经尝试了大量的排列,包括将整个事物转换为数组(这违反了原始问题中的效率限制)。我觉得有一件小事我没有得到,我想知道是否有人可以给我一个正确方向的推动?

My major issue is that the last character of the original string keeps getting overwritten by the subsequent iterations of the loop. I've tried a great number of permutations, including converting the whole thing to arrays (which violates the efficiency restriction in the original problem). I feel like there's just a tiny thing I'm not getting, and I was wondering if someone could give me a nudge in the right direction?

谢谢!

推荐答案

你想要的是拆分位于 k 的字符串,并将两个部分再次合并在一起,但顺序相反。
主要问题是 k 可能大于或等于字符串的大小。因此,您需要再次将 k 带入有效范围。

What you want is to split the string at position k and merge both parts together again but in reverse order. The main problem is that k may be greater than or equal to the size of your string. So you need to bring k into a valid range again.

public static String cyclicLeftShift(String s, int k){
    k = k%s.length();
    return s.substring(k) + s.substring(0, k);
}

测试方法:

public static void main(String[] args)
{
    String test = "Hello World";
    for(int i = 0; i < test.length()*3; i++)
        System.out.println(cyclicLeftShift(test, i));
}

输出:

Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
 WorldHello
WorldHello 
orldHello W
rldHello Wo
ldHello Wor
dHello Worl

这篇关于将字符串中的字符向左移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆