美文网首页
java 字符串单词交换 hello world world h

java 字符串单词交换 hello world world h

作者: 下午2点14分 | 来源:发表于2018-06-29 10:21 被阅读13次

    看到同事出去的面试题,将“hello world” 转换成 “ world hello"还要考虑空间复杂度

    然后就随便写写,主要是c思路,用c语言估计可以更简洁,也不知道是不是面试官想要的答案

    String s = "hello world 123 321";

    Field f = s.getClass().getDeclaredField("value");

    f.setAccessible(true);

    char[] chrs = (char[]) f.get(s);

    char temp;

    for (int i = 0; i < chrs.length / 2; i++) {

              temp = chrs[i];

              chrs[i] = chrs[chrs.length - i - 1];

              chrs[chrs.length - i - 1] = temp;

    }

    System.out.println(s);

    int lastIndex = 0;

    for (int i = 0; i < chrs.length; i++) {

             if (chrs[i] == ' ' || i == chrs.length - 1) {

                         if (i == chrs.length - 1)

                         i = i + 1;

                         for (int j = lastIndex; j < lastIndex + (i - lastIndex) / 2; j++) {

                                    temp = chrs[j];

                                    chrs[j] = chrs[i - j - 1 + lastIndex];

                                     chrs[i - j - 1 + lastIndex] = temp;

                            }

                  lastIndex = i + 1;

                }

    }

    System.out.println(s);

    相关文章

      网友评论

          本文标题:java 字符串单词交换 hello world world h

          本文链接:https://www.haomeiwen.com/subject/uewoyftx.html