存储以长度为键的字符串的关联数组(Store associative array of strings with length as keys)
我有这个输入:
5 it your reality real our第一行是后来的字符串数。 我应该这样存储它(伪代码):
associative_array = [ 2 => ['it'], 3 => ['our'], 4 => ['real', 'your'], 7 => ['reality']]如您所见,关联数组的键是存储在内部数组中的字符串的长度。 那么我怎么能在java中做到这一点? 我来自php世界,所以如果你将它与php进行比较,那将是非常好的。
I have this input:
5 it your reality real ourFirst line is number of strings comming after. And i should store it this way (pseudocode):
associative_array = [ 2 => ['it'], 3 => ['our'], 4 => ['real', 'your'], 7 => ['reality']]As you can see the keys of associative array are the length of strings stored in inner array. So how can i do this in java ? I came from php world, so if you will compare it with php, it will be very well.
最满意答案
djechlin已经发布了一个更好的版本,但这里只是使用JDK类的一个完整的独立示例:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String firstLine = reader.readLine(); int numOfRowsToFollow = Integer.parseInt(firstLine); Map<Integer,Set<String>> stringsByLength = new HashMap<>(numOfRowsToFollow); //worst-case size for (int i=0; i<numOfRowsToFollow; i++) { String line = reader.readLine(); int length = line.length(); Set<String> alreadyUnderThatLength = stringsByLength.get(length); //int boxed to Integer if (alreadyUnderThatLength==null) { alreadyUnderThatLength = new HashSet<>(); stringsByLength.put(length, alreadyUnderThatLength); } alreadyUnderThatLength.add(line); } System.out.println("results: "+stringsByLength); } }它的输出如下:
3 bob bart brett results: {4=[bart], 5=[brett], 3=[bob]}djechlin already posted a better version, but here's a complete standalone example using just JDK classes:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String firstLine = reader.readLine(); int numOfRowsToFollow = Integer.parseInt(firstLine); Map<Integer,Set<String>> stringsByLength = new HashMap<>(numOfRowsToFollow); //worst-case size for (int i=0; i<numOfRowsToFollow; i++) { String line = reader.readLine(); int length = line.length(); Set<String> alreadyUnderThatLength = stringsByLength.get(length); //int boxed to Integer if (alreadyUnderThatLength==null) { alreadyUnderThatLength = new HashSet<>(); stringsByLength.put(length, alreadyUnderThatLength); } alreadyUnderThatLength.add(line); } System.out.println("results: "+stringsByLength); } }its output looks like this:
3 bob bart brett results: {4=[bart], 5=[brett], 3=[bob]}更多推荐
发布评论