地址:https://www.hackerrank.com/domains/java/java-data-structure
题目https://www.hackerrank.com/challenges/java-list
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int n = in.nextInt();
LinkedList<Integer> l = new LinkedList<Integer>();
for(int i = 0;i < n;i++)
l.add(in.nextInt());
int q = in.nextInt();
while(q-- > 0){
String op = in.next();
if(op.equals("Insert")){
int x = in.nextInt(),y = in.nextInt();
l.add(x,y);
}
else{
int x = in.nextInt();
l.remove(x);
}
}
for(int x : l)
System.out.print(x + " ");
}
}
题目:https://www.hackerrank.com/challenges/phone-book
题意:使用map
思路:以前好像没怎么用过.nextLine()
.nextLine()
用来读入一行数据,这个和C++已经取消的gets相似,都会读入换行,如果使用前有读入数据的话,提前读入空行.nextLine()
防止影响后面的读入。
代码:
//Complete this code or write your own from scratch
import java.util.*;
import java.io.*;
class Solution{
public static void main(String []argh)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
HashMap<String,Integer> mp = new HashMap<String,Integer>();
while(n-- > 0){
String name = in.nextLine();
int number = in.nextInt();
mp.put(name, number);
in.nextLine();
}
while(in.hasNext()){
String name = in.nextLine();
if(mp.containsKey(name))
System.out.println(name + "=" + mp.get(name));
else
System.out.println("Not found");
}
}
}
题目:https://www.hackerrank.com/challenges/java-stack/problem
代码:
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String s = in.next();
Stack<Character> st = new Stack<Character>();
for(int i = 0;i < s.length();i++){
if(!st.empty()){
switch(s.charAt(i)){
case ')':
if(st.peek() == '(')
st.pop();
break;
case ']':
if(st.peek() == '[')
st.pop();
break;
case '}':
if(st.peek() == '{')
st.pop();
break;
default:
st.push(s.charAt(i));
}
}
else
st.push(s.charAt(i));
}
if(st.empty())
System.out.println("true");
else
System.out.println("false");
}
}
}
题目:https://www.hackerrank.com/challenges/java-hashset/problem
代码: