题解 | #倒置字符串#

倒置字符串

http://www.nowcoder.com/questionTerminal/b0ae3d72444a40e2bb14af7d4cb856ba

比如:I like beijing.
思路:
第一步,字符串整体逆置,得到:.gnijieb ekil I
第二步,将字符串中每一个单词逆置,得到:beijing. like I
  • 数组转为字符,直接输出Arrays.toString(ch)不能通过测试,必须再创建一个字符串,把ch传入。
  • 因为Java没有适合的库函数的逆置,需要自己写出来。
  • 字符串转换为字符数组 toCharArray()
  •  




import java.util.*;

public class Main {
    public static void reverse(char[] ch, int start, int end){
        //倒置字符串方法
        while (start < end) {
            char ret = ch[start];
            ch[start] = ch[end];
            ch[end] = ret;
            start++;
            end--;
        }
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String s = in.nextLine();
            char[] ch = s.toCharArray();
            int len = ch.length;
            //倒置整个字符串
            reverse(ch, 0, len - 1);
            
            //倒置每个单词
            int i = 0;
            while (i < len) {
                int j = i;
                while(j < len && ch[j] != ' '){
                    j++;
                }
                if (j < len) {
                    reverse(ch, i, j - 1);
                    i = j + 1;
                } else {
                    //字符串最后一个单词,
                    reverse(ch, i , j - 1);
                    i = j;
                }
            }
            String s2 = new String(ch);
            System.out.println(s2);
        }
    }
}


全部评论

相关推荐

1 1 评论
分享
牛客网
牛客企业服务