在我最近的期中考试中,我被问到要把一个大字符串分成两个相等的小字符串,然后再将两个较小的字符串分成两半的问题。我知道必须对此问题进行递归处理,但是我不知道如何将其应用于Java代码。
任何帮助都会很棒,谢谢。
public class Question7a {
public static void main(String[] args) {
String strings = "aaaa bbbb cccc dddd";
Question7a question7a = new Question7a();
question7a.splitString(strings);
}
public void splitString(String words){
int m = words.length() / 2; //gets the middle length of the string to split there.
for (int i=0; i < m; i++) {
String[] halves = {words.substring(0, m), words.substring(m)};
System.out.println(halves[0]); //first half of the string
System.out.println(halves[1]); //second part
if(halves[0].equals(true)){
int m2 = halves.length/2; //Intent was to get the middle of the new half.
halves[0] = {hal.substring(0, m2), words.substring(m2)};
halves[1] = {words.substring(0, m2), words.substring(m2)};
System.out.println(halves[0]);
System.out.println(halves[1]);
}
else{
System.out.println("Null");
}
}
}
想要输出类似以下内容的
"aaaa bbbb" cccc dddd
| |
| |
"aaaa" "bbbb" cccc dddd
| |
| |
"aa" "aa" "bb" "bb"
另一半类似(不确定是否是正确的查看方式)。
答案 0 :(得分:3)
尝试一下:
import java.util.Stack;
class Hackerearth{
public static void main(String args[] ) throws Exception {
Stack<String> st = new Stack<>();
String str = "aaaa bbbb cccc dddd";
st.push(str);
split(st);
}
public static void split(Stack<String> st){
while(!st.empty()){
String s = st.pop();
if(s.length() == 1){
System.out.println(s);
}
else{
int mid = s.length() / 2;
String first = s.substring(0, mid);
String second = s.substring(mid, s.length());
st.push(second);
st.push(first);
}
}
}
}
您可以在Java.util包中使用Stack。它具有预定义的push和pop方法来添加和删除项目。.Stack Documentation