活跃农民
- 积分
- 822
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-2-18
- 最后登录
- 1970-1-1
|
本帖最后由 capricornhx 于 2022-4-9 02:47 编辑
- import java.util.List;
- import java.util.ArrayList;
- public class Solution {
-
- // recursion
- public List<String> splitStr(String input) {
- if (input.equals("")){
- return new ArrayList<String>();
- } else {
- if (!input.startsWith("\"")) {
- int cutoff = input.indexOf(", ");
- List<String> lst = new ArrayList<String>();
- lst.add(input.substring(0, cutoff));
- lst.addAll(splitStr(input.substring(cutoff + 2)));
- return lst;
- } else {
- int cutoff = input.indexOf("\", ");
- List<String> lst = new ArrayList<String>();
- lst.add(input.substring(1, cutoff));
- lst.addAll(splitStr(input.substring(cutoff + 3)));
- return lst;
- }
- }
- }
-
- public static void main(String[] args) {
- String input = "1.hello, 2.this is a test message, \"3.this has quotes, treat me as same message, thanks\", \"4.this is another message\"";
- input = input + ", ";
- Solution sol = new Solution();
- List<String> result = sol.splitStr(input);
- for (int i = 0; i < result.size(); i++){
- System.out.println(result.get(i));
- }
- }
- }
复制代码 我试着做了一下这个题,貌似适合用recursion?我写的比较繁琐,不知道楼主有没有更好的写法 |
|