简介
面试的时候被问到的一道题,大概题目意思是:
给定一个字符串"12345678987",然后进行反转(反转的结果是:“79867823451”)
并且,反转后过程中要在中间加上"-“号
插入时机:每隔1,2,3,4,5…数插入一个”-",最后如果有剩余的,直接拿过来
最后的结果是:“7-98-678-2345-1”
思路
首先,进行边界条件判断;
设置一个指针index,指向最后一个元素的下一个元素,即:index = 数组长度
设置一个变量count = 1,记录这次需要转移几个元素
设置一个新的数组r(resultArray),用来接收新的数据
设置一个newIndex,指向r数组中将要插入的位置
遍历index - count 到 index的元素,将每一个元素加到新数组中去
遍历完后,将index指向的元素向后移动count个数:index = index - count;
count++;
最后,将剩余的数据,一个一个加入新的数组中去
当时写了一个答案,回来的时候发现调试不通,中间有错误,回来后自己按照之前的写法又调试了一番,算是调试通了,做下记录:
package com.yz01;
public class test6 {
public static void main(String[] args) {
String s = "12345678987";
System.out.println(s);
char[] c = test(s);
System.out.println(c);
}
public static char[] test(String s) {
//边界条件
if (s == null || s.length() == 0) return null;
//字符串转换为数组
char[] c = s.toCharArray();
//新建一个结果数组,用来存放新的数组,因为加了-,所以需要扩容
//此处写成动态数组比较好
char[] r = new char[c.length * 2];
//新数组需要插入的位置
int newIndex = 0;
//每次需要间隔1,2,3...插入一个-
int count = 1;
//count变值条件
int jiShuQi = 0;
//从旧数组最后开始遍历
for (int i = c.length - 1; i >= 0; i--) {
//旧数组的值,赋值给新数组的值
r[newIndex] = c[i];
//新数组index加1
newIndex++;
//count的计数器+1
jiShuQi++;
//如果计数器的值,等于count
if(jiShuQi == count){
//count++
count++;
//计数器清空,从头开始
jiShuQi = 0;
//插入-
r[newIndex++] = '-';
}
}
return r;
}
}
运行结果:
I/System.out: 12345678987
I/System.out: 7-89-876-5432-1��������������
– 2024-03-05 –
结果还是有点不对
题目要求的是:
“12345678987”
转换为:
“7-98-678-2345-1”
而实际上转成了:
“7-89-876-5432-1”
因为,再次进行优化:
public class test6 {
public static void main(String[] args) {
String s = "12345678987";
System.out.println(s);
char[] c = test(s);
//把?去掉
for (int i = 0; i < c.length; i++){
if(c[i] != '?'){
System.out.print(c[i]); // 012345
}
}
System.out.println();
}
public static char[] test(String s) {
//边界条件
if (s == null || s.length() == 0) return null;
//字符串转换为数组
char[] charArray = s.toCharArray();
//新建一个结果数组,用来存放新的数组,因为加了-,所以需要扩容
//此处写成动态数组比较好
char[] resultArray = new char[charArray.length * 2];
for (int i = 0; i < resultArray.length; i++){
resultArray[i] = '?';
}
//新数组需要插入的位置
int newIndex = 0;
//每次需要间隔1,2,3...插入一个-
int count = 1;
//count变值条件
int jiShuQi = 0;
//从旧数组最后开始遍历
for (int i = charArray.length - 1; i >= 0; i--) {
//旧数组的值,赋值给新数组的值
resultArray[newIndex] = charArray[i];
//新数组index-1
newIndex--;
//count的计数器+1
jiShuQi++;
//如果计数器的值,等于count
if(jiShuQi == count){
count++;
//计数器清空,从头开始
jiShuQi = 0;
//将newIdnex回归到原位,该位置做插入*操作
newIndex = newIndex + count;
//插入-
resultArray[newIndex] = '-';
//指向 分割数组 的最后一个元素
newIndex = newIndex + count;
}
}
return resultArray;
}
}
运行结果:
I/System.out: 12345678987
I/System.out: 7-98-678-2345-1