每日一练16——Java反转传入的字符串字符(8kyu)

题目

完成一个解决方案,使其反转传入它的字符串字符。

Kata.solution("world") //returns "dlrow"

SampleTests:

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void sampleTests() {
      assertEquals("dlrow", Kata.solution("world"));
    }
}

答题:

我生硬的答案:

字符数组元素前后交换。

public class Kata {

    public static String solution(String str) {
        if (str == null || str.equals("")) {
            return "";
        }
        char[] arr = str.toCharArray();
        char tmp;
        for (int i = 0, end = arr.length - 1; i < end - i; i++) {
            tmp = arr[i];
            arr[i] = arr[end - i];
            arr[end - i] = tmp;
        }
        return new String(arr);
    }
    
}

别人家的大牛:

  1. 机智型,利用官方库函数一步到位
public class Kata {

  public static String solution(String str) {
    return new StringBuilder(str).reverse().toString();
  }

}
  1. 务实型,从后往前提取字符到新字符串
public class Kata {

    public static String solution(String str) {
        StringBuilder newcad = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            newcad.append(str.charAt(i));
        }
        return newcad.toString();
    }

}

思考

其实我也想到了,倒置的reverse()方法,但是不熟呀,想想还是得写写土办法,锻炼一下哈。

你可能感兴趣的:(每日一练16——Java反转传入的字符串字符(8kyu))