• 《程序员代码面试指南》第五章 字符串问题 翻转字符串


    题目

    翻转字符串
    

    java代码

    package com.lizhouwei.chapter5;
    
    /**
     * @Description: 翻转字符串
     * @Author: lizhouwei
     * @CreateDate: 2018/4/25 20:09
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter5_11 {
    
        public String reverse(String str) {
            if (str == null) {
                return null;
            }
            char[] chars = str.toCharArray();
            reverse(chars, 0, chars.length - 1);
            int start = -1;
            int end = -1;
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] != ' ') {
                    start = i == 0 || chars[i - 1] == ' ' ? i : start;
                    end = i == chars.length - 1 || chars[i + 1] == ' ' ? i : end;
                }
                if (start != -1 && end != -1) {
                    reverse(chars, start, end);
                    start = -1;
                    end = -1;
                }
            }
    
            return String.valueOf(chars);
        }
        public String reverseByK(String str,int k) {
            if (str == null) {
                return null;
            }
            char[] chars = str.toCharArray();
            reverse(chars, 0,k-1);
            reverse(chars, k,chars.length - 1);
            reverse(chars, 0, chars.length - 1);
            return String.valueOf(chars);
        }
        public void reverse(char[] chars, int start, int end) {
            char temp = ' ';
            while (start < end) {
                temp = chars[start];
                chars[start++] = chars[end];
                chars[end--] = temp;
            }
        }
    
        //测试
        public static void main(String[] args) {
            Chapter5_11 chapter = new Chapter5_11();
            String str1 = "dog loves pig";
            String result1 = chapter.reverse(str1);
            System.out.println("dog loves pig 翻转:" + result1);
            String str2 = "1234567ABCD";
            String result2 = chapter.reverseByK(str2,7);
            System.out.println("1234567ABCD 左半区和右半区调整:" + result2);
         }
    }
    
    

    结果

  • 相关阅读:
    5059 一起去打CS
    2439 降雨量
    vijos P1037搭建双塔
    4979 数塔
    2596 售货员的难题
    P2342 叠积木
    1540 银河英雄传说
    1051 接龙游戏
    hdu1251
    洛谷P1717 钓鱼
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8947602.html
Copyright © 2020-2023  润新知