【问题标题】:How to change input String entry format from txt file reading如何从 txt 文件读取中更改输入字符串条目格式
【发布时间】:2020-10-28 13:05:17
【问题描述】:

我有这个输入:

["joe","oej","rat","tar","art","atb","tab"]

使用此代码:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<String, List>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if (!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
}

它正确地给了我这个输出:

[["rat","tar","art"],["atb","tab"],["joe","oej"]]

但是,输入和输出的格式并不是我想要的。

我希望输入文件是一个名为 input.txt 的 txt 文件,并在其中显示为;

joe
oej
rat
tar
art
atb
tab

并将输出存储在一个名为 output.txt 的新 txt 文件中;

atb tab
joe oej
art rat tar

我试图读取输入 txt 文件的内容在我的主要内容中:

File file = new File(args[0]);
Scanner scan = new Scanner(file);

并写入我的输出文件:

FileWriter writer = new FileWriter("output.txt");
writer.write(fileContent);
writer.close();

我的问题是:第二个字母段可以简单地实现到class Solution吗?

【问题讨论】:

    标签: java string file input output


    【解决方案1】:

    如果我理解正确,您想从文件中读取输入并将输出直接写入解决方案类中的文件。为此,您可以在解决方案中创建一个新方法,并在调用 groupAnagrams 之前和之后添加该逻辑。

    class Solution {
        public void fromFile(String inputFilename){
            // Open the file inputFilename here
            // Read the lines into a string array
            List<List<String>> groupAnagrams(strs);
            // Create the output file
            // Write the result in the file
        }
        public List<List<String>> groupAnagrams(String[] strs) {
            //...
        }
    }
    

    这样你就不需要改变方法groupAnagram了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多