zoukankan      html  css  js  c++  java
  • 翻转字符串

    比如字符串“dog loves pig”,翻转成“pig loves dog”

    “how are you”翻转成“you are how”

    思路是把字符串整体逆序,然后找到每个单词,再把每个单词的字符逆序一遍

    可是现在的面试要求就是不能用String,不能用库函数

    给定你的就是字符数组char[] c = new char[] {'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u'};

    当然要求不能用String s = new String(c);不能操作字符串。

    以下思路参考左程云的书:

    import java.util.Scanner;
    
    public class Main {
        public static void rotateWord(char[] chas) {
            if (chas == null || chas.length == 0) {
                return;
            }
            reverse(chas, 0, chas.length - 1);
            int l = -1;
            int r = -1;
            int len = chas.length;
            for (int i = 0; i < len; ++i) {
                // 这个字符不为空格,如果前一个为空,则记录l,如果后一个为空,则记录r
                // 若为起始点或者最后,直接记录,主要考虑只有一个单词情况
                if (chas[i] != ' ') {
                    l = i == 0 || chas[i - 1] == ' ' ? i : l;
                    r = i == len - 1 || chas[i + 1] == ' ' ? i : r;
                }
                if (l != -1 && r != -1) {
                    reverse(chas, l, r);
                    l = -1;
                    r = -1;
                }
            }
        }
    
        private static void reverse(char[] chas, int start, int end) {
            char temp = 0;
            while (start < end) {
                temp = chas[start];
                chas[start] = chas[end];
                chas[end] = temp;
                ++start;
                --end;
            }
        }
    
        public static void main(String[] args) {
            Scanner cin = new Scanner(System.in);
            String s = cin.nextLine();
            cin.close();
            char[] c = s.toCharArray();
            // ===================================
            rotateWord(c); // 这里为需要编写的代码
            // ===================================
            for (char cc : c) {
                System.out.print(cc);
            }
            System.out.println();
        }
    }

    =========================Talk is cheap, show me the code=======================

    CSDN博客地址:https://blog.csdn.net/qq_34115899
  • 相关阅读:
    java.io.EOFException ValueOperations.increment()操作后,获取值时有的bug
    使用maven profile指定配置文件打包适用多环境
    关于3Q大战和反垄断
    在ECUG2010上的演讲稿
    让Windows7在启动时自动挂载虚拟磁盘
    也谈并行计算(一)C#版的Parallel.For实现
    给.NET的string类添加一个命令行参数分解的扩展
    顺序表 code
    很高兴开始博客之旅 code
    (原)前端知识杂烩(css系列)
  • 原文地址:https://www.cnblogs.com/lcy0515/p/10807857.html
Copyright © 2011-2022 走看看