字符串翻转(Java)

今天面试,面试官问了我一个这样的问题,比如ab..dd….scd…df这样一个字符串,把它翻转成df…scd….dd..ab,让我在稿纸上coding出来,当时思路极为混乱,现在coding出来以作记录。

import java.util.Scanner;
import java.util.Stack;

public class test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.next();
            System.out.println(getNewStr(str));
        }
    }

    public static String getNewStr(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        Stack<String> stack = new Stack<String>();
        char[] ch = str.toCharArray();
        int i = 0;
        while (i < str.length()) {
            if (ch[i] != '.') {
                int count = 0;
                int begin = i;
                while (i < str.length() && ch[i] != '.') {
                    i++;
                    count++;
                }
                stack.push(str.substring(begin, begin + count));
            } else {
                int begin = i;
                int count = 0;
                while (i < str.length() && ch[i] == '.') {
                    count++;
                    i++;
                }
                stack.push(str.substring(begin, begin + count));
            }
        }
        StringBuffer sb = new StringBuffer();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.toString();
    }
}
点赞