GuilinDev

Lc0917

05 August 2008

917 Reverse Only Letters

字符串中只reverse字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String reverseOnlyLetters(String S) {
    StringBuilder sb = new StringBuilder(S);
    for (int i = 0, j = S.length() - 1; i < j;) {
        if (!Character.isLetter(sb.charAt(i))) {
            ++i;
        } else if (!Character.isLetter(sb.charAt(j))) {
            --j;
        } else {
            sb.setCharAt(i, S.charAt(j));
            sb.setCharAt(j--, S.charAt(i++));
        }
    }
    return sb.toString();
}