题目1:给一段字符串在不用其他数据结构或者API的情况下,反转字符串。尽可能考虑其性能问题
String str = "abc146d3e2f";
倒着取字符串
private static void reverse1(String str) {
char [] ch = new char[str.length()];
for(int i=str.length()-1,k=0;i>=0;i--,k++) {
ch[k] = str.charAt(i);
}
System.out.println(ch);
}
//循环次数减半。
private static void reverse(String str) {
char [] ch = str.toCharArray();
int len = ch.length % 2 == 0 ? ch.length / 2: ch.length / 2 +1;
int max = ch.length -1 ;
for (int i = 0; i < len; i++) {
char temp = ch[max];
ch[max--] = str.charAt(i);
ch[i] = temp;
}
System.out.println(ch);
}
题目2:给出一段字符串,取出数字。
String str = "abc146d3e2f";
//利用正则
private static void filterLetter1(String str1) {
Set<Character> set = new TreeSet<>();
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = null;
for (int i = 0; i < str1.length(); i++) {
isNum = pattern.matcher(str1.substring(i, i + 1));
if (isNum.matches()) {
set.add(str1.charAt(i));
}
}
System.out.println(set);
}
//利用ascii码特征过滤
private static void filterLetter(String str1) {
char[] arr = str1.toCharArray();
StringBuffer sb = new StringBuffer();
Set<Character> set = new TreeSet<>();
for (int i = 0; i < arr.length; i++) {
int num = (int) arr[i];
if (num < 97) {
sb.append((char) num);
}
}
System.out.println(set);
}
题目3:将一组数组完全打乱
int [] arr = new int []{1,2,3,4,5,6,7,8}
private static void scatter(int[] arr) {
int count = 0;
while (count < 8) {
int random = (int) (Math.random() * 8);
if (arr[random] > 0) {
System.out.print(arr[random]);
arr[random] = 0;
count++;
}
}
}