面试题:一个字符串包含英文和特殊字符,特殊字符不变,英文顺序反过来,比如string str="f!dw@" 变成"w!df@"。要考虑 时间复杂度,性能问题。

public class Reverse {

    public static void main(String[] args) {
        String str = "w@dj!tk";
        char[] chars = str.toCharArray();
        for (int i = 0, j = chars.length - 1; i < j; j--, i++) {
            if (!isEnglish(String.valueOf(chars[i]))) {
                i++;
            }
            if (!isEnglish(String.valueOf(chars[j]))) {
                j--;
            }
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
        }
        for (int x = 0; x < chars.length; x++) {
            System.out.print(chars[x]);
        }
    }

    private static boolean isEnglish(String ch){
        return ch.matches("^[a-zA-Z]*");
    }
}

结果:

k@tj!dw

猜你喜欢

转载自blog.csdn.net/liu59412/article/details/82866192