0% found this document useful (0 votes)
4 views22 pages

Collections in Java

The document provides an overview of the Java Collection Framework, detailing its architecture for storing and manipulating groups of objects. It covers various interfaces and classes such as Collection, List, Set, Queue, and Deque, along with their methods and implementations like ArrayList, LinkedList, HashSet, and PriorityQueue. Additionally, it highlights the differences between ArrayList and LinkedList, emphasizing their internal storage mechanisms and performance characteristics.

Uploaded by

priyapriya43166
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Collections in Java

The document provides an overview of the Java Collection Framework, detailing its architecture for storing and manipulating groups of objects. It covers various interfaces and classes such as Collection, List, Set, Queue, and Deque, along with their methods and implementations like ArrayList, LinkedList, HashSet, and PriorityQueue. Additionally, it highlights the differences between ArrayList and LinkedList, emphasizing their internal storage mechanisms and performance characteristics.

Uploaded by

priyapriya43166
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Collections in Java

1. Java Collection Framework


2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No Method Description
.

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection elements in the
extends E> c) invoking collection.

3 public boolean remove(Object It is used to delete an element from the collection.


element)

4 public boolean removeAll(Collection<? It is used to delete all the elements of the specified
> c) collection from the invoking collection.

5 default boolean removeIf(Predicate<? It is used to delete all the elements of the collection that
super E> filter) satisfy the specified predicate.

6 public boolean retainAll(Collection<?> It is used to delete all the elements of invoking collection
c) except the specified collection.

7 public int size() It returns the total number of elements in the collection.

8 public void clear() It removes the total number of elements from the
collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean containsAll(Collection<? It is used to search the specified collection in the collection.
> c)

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of
the returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its
source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the
collection.

18 public boolean equals(Object element) It matches two collections.

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. Method Description

1 public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the next element.

3 public void remove() It removes the last elements returned by the iterator. It is less used.

The Iterable interface is the root interface for all the collection classes. The Collection interface
extends the Iterable interface and therefore all the subclasses of Collection interface also implement
the Iterable interface.

It contains only one abstract method. i.e.,


1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which
we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the
following example.

import [Link].*;
class ArrayList1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

//Traversing list through Iterator


Iterator itr=[Link]();
while([Link]())
[Link]([Link]());
}
}

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized.

In LinkedList, the manipulation is fast because no shifting is required.

import [Link].*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());
}
}

Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework.

import [Link].*;
public class vector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");

Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());

}
}

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.

import [Link].*;
class stack1{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link](stack);
/*
Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());
*/
}
}

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used
to hold the elements which are about to be processed. There are various classes like PriorityQueue,
Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
1. Queue<String> q1 = new PriorityQueue();
2. Queue<String> q2 = new ArrayDeque();

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are
to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

What is PriorityQueue in Java?

 A queue follows First-In-First-Out algorithm, in case of PriorityQueue queue


elements are processed according to the priority (ordered as per their natural ordering
or based on a custom Comparator supplied at the time of creation).

 The PriorityQueue is based on the priority heap.


 We can’t create PriorityQueue of Objects that are non-comparable
Inserting null into a PriorityQueue will throw a NullPointerException, as
PriorityQueue in Java does not permit null elements.

 PriorityQueue are unbound queues.


 The queue retrieval operations poll, remove, peek, and element access the element at
the head of the queue.
 Inserting an element (offer()) and deleting an element (poll()) in a PriorityQueue both
have a time complexity of O(log n), where n is the number of elements in the queue.
 The default PriorityQueue is implemented with Min-Heap, which means the top
element is the minimum one in the heap. If we want to implement a max-heap, we
need to use our custom Comparator.
Internally, the PriorityQueue in Java uses an array to store its elements. This array
automatically grows in size if the initial capacity (which is 11 by default in JDK 17) is
not large enough to hold all the elements added to the queue.
 While you don’t have to specify an initial capacity when creating a PriorityQueue, if
you know how many elements you’ll be adding ahead of time, it’s beneficial to set an
initial capacity. This helps prevent the queue from frequently resizing, which can use
up unnecessary CPU resources that could be better utilized elsewhere.

Can you provide an example scenario where a PriorityQueue would be useful?


A PriorityQueue can be used in scenarios such as task scheduling in an operating system,
where tasks with higher priority need to be executed before those with lower priority.

PriorityQueue Constructors

 PriorityQueue(): Creates a PriorityQueue with the default initial capacity (which is


11) that orders its elements according to their natural ordering.
 PriorityQueue(Collection c): It creates a PriorityQueue containing the elements in
the specified collection.
 PriorityQueue(int initialCapacity): Creates a PriorityQueue with the specified
initial capacity that orders its elements according to their natural ordering.
 PriorityQueue(int initialCapacity, Comparator comparator): Creates a
PriorityQueue with the specified initial capacity that orders its elements according to
the specified comparator.
 PriorityQueue(PriorityQueue c): Creates a PriorityQueue containing the elements in
another priority queue.
 PriorityQueue(SortedSet c): Creates a PriorityQueue containing the elements in the
specified sorted set.

PriorityQueue operations

 boolean add(E element) inserts the specified element into this priority queue.
 boolean offer(E e) method is used to insert a specific element into the priority queue.
 public peek() retrieves, but does not remove, the head of this queue, or returns null if
this queue is empty.
 public poll() retrieves and removes the head of this queue, or returns null if this queue
is empty.
 public remove() removes a single instance of the specified element from this queue,
if it is present. When we remove an element from the priority queue, the least element
according to the specified ordering is removed first.
 Iterator iterator() returns an iterator over the elements in this queue.
boolean contains(Object o) method returns true if this queue contains the specified
element
 void clear() is used to remove all of the contents of the priority queue.
 int size() returns the number of elements present in the set.
 toArray() is used to return an array containing all of the elements in this queue.
 Comparator comparator() method is used to return the comparator that can be used
to order the elements of the queue.

import [Link].*;
class priorityQueue1{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");

//[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]();
[Link]("head:"+[Link]());
[Link]();
[Link]("head:"+[Link]());
[Link]();
[Link]("head:"+[Link]());

[Link]("iterating the queue elements:");


Iterator itr=[Link]();
while([Link]())
[Link]([Link]());

[Link]();
[Link]();
[Link]("after removing two elements:");
Iterator<String> itr2=[Link]();
while([Link]())
[Link]([Link]());

}
}

// Creating empty priority queue


PriorityQueue<Integer> pQueue
= new PriorityQueue<Integer>(
[Link]());

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended queue which enables us to perform the operations
at both the ends.
Deque can be instantiated as:
1. Deque d = new ArrayDeque();

ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue,
we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

import [Link].*;
public class ArrayDeque1{
public static void main(String[] args) {

Deque<String> deque = new ArrayDeque<String>();


[Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
[Link]("Vijay");

for (String str : deque)


[Link](str);

[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}

Set Interface
Set Interface in Java is present in [Link] package. It extends the Collection interface. It represents
the unordered set of elements which doesn't allow us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
import [Link].*;
public class set1{
public static void main(String args[]){

HashSet<String> set=new HashSet<String>();


[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());

}
}

LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.

import [Link].*;
public class set1{
public static void main(String args[]){

HashSet<String> set=new LinkedHashSet<String>();


[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());
}
}

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

import [Link].*;
public class TreeSet1{
public static void main(String args[]){

TreeSet<String> set=new TreeSet<String>();


[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]())
[Link]([Link]());

}
}

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to store the LinkedList internally uses a doubly linked list to
elements. store the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is removed from ArrayList because it uses a doubly linked list, so no
the array, all the other elements are shifted in memory. bit shifting is required in memory.

3) An ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

5) The memory location for the elements of an ArrayList The location for the elements of a linked list is not
is contiguous. contagious.

6) Generally, when an ArrayList is initialized, a default There is no case of default capacity in a LinkedList.
capacity of 10 is assigned to the ArrayList. In LinkedList, an empty list is created when a
LinkedList is initialized.

7) To be precise, an ArrayList is a resizable array. LinkedList implements the doubly linked list of the
list interface.

Sort list: [Link]();

Basis Array ArrayList

Definition An array is a dynamically-created object. It serves The ArrayList is a class of


as a container that holds the constant number of Java Collections framework. It contains
values of the same type. It has a contiguous popular classes like Vector, HashTable,
memory location. and HashMap.

Static/ Array is static in size. ArrayList is dynamic in size.


Dynamic

Resizable An array is a fixed-length data structure. ArrayList is a variable-length data


structure. It can be resized itself when
needed.

Initialization It is mandatory to provide the size of an array We can create an instance of ArrayList
while initializing it directly or indirectly. without specifying its size. Java creates
ArrayList of default size.

Performance It performs fast in comparison to ArrayList ArrayList is internally backed by the


because of fixed size. array in Java. The resize operation in
ArrayList slows down the performance.

Primitive/ An array can store We cannot store primitive type in


Generic type both objects and primitives type. ArrayList. It automatically converts
primitive type to object.

Iterating We use for loop or for each loop to iterate over We use an iterator to iterate over
Values an array. ArrayList.

Type-Safety We cannot use generics along with array because ArrayList allows us to store
it is not a convertible type of array. only generic/ type, that's why it is
type-safe.

Length Array provides a length variable which denotes ArrayList provides the size() method to
the length of an array. determine the size of ArrayList.

Adding We can add elements in an array by using Java provides the add() method to add
Elements the assignment operator. elements in the ArrayList.

Single/ Multi- Array can be multi-dimensional. ArrayList is always single-dimensional.


Dimensional

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current Vector increments 100% means doubles the array size if the total
array size if the number of elements number of elements exceeds than its capacity.
exceeds from its capacity.

3) ArrayList is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e., in a multithreading
synchronized. environment, it holds the other threads in runnable or non-
runnable state until current thread releases the lock of the object.

5) ArrayList uses the Iterator interface to A Vector can use the Iterator interface or Enumeration interface
traverse the elements. to traverse the elements.
/*
You are given a 0-indexed array of strings words and a character x.

Return an array of indices representing the words that contain the character x.

Note that the returned array may be in any order.

Example 1:

Input: words = ["leet","code"], x = "e"


Output: [0,1]
Explanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1.
Example 2:

Input: words = ["abc","bcd","aaaa","cbc"], x = "a"


Output: [0,2]
Explanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2.
Example 3:

Input: words = ["abc","bcd","aaaa","cbc"], x = "z"


Output: []
Explanation: "z" does not occur in any of the words. Hence, we return an empty array.
*/

import [Link].*;
class ArrayListAssign1
{
static List<Integer> findWordsContaining(List<String> words, char x) {
List<Integer> ans = new ArrayList<>();
int n = [Link]();
for (int i = 0; i < n; i++) {
for (char j : [Link](i).toCharArray()) {
if (j == x) {
[Link](i);
break;
}
}
}
return ans;
}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
List<String> list=new ArrayList<>();

String s=[Link]();
String[] sarr=[Link](" ");
for( int i=0;i<[Link];i++)
[Link](sarr[i]);

char c=[Link]().charAt(0);
[Link](findWordsContaining(list,c));
}
}

/*
public List<Integer> findWordsContaining(List<String> words, char x) {
int N = [Link]();
List<Integer> ans = new ArrayList<>();

for (int i = 0; i < N; i++) {


if ([Link](i).indexOf(x) != -1)
[Link](i);
}
return ans;
}
*/

Rahul and Rohith are playing a switch game.


Rahul has given a string PresentState that contains only '+' and '-' . Both take turns to switch two
consecutive "++" into "--" . The game ends when a person can no longer make a move, and therefore
the other person will be the winner.
Return all possible states of the string presentState after one valid move. You may return the answer
in any [Link] there is no valid move, return an empty list [] .

Input Format:
-------------
Line-1: A string represents present state.

Output Format:
--------------
Array of strings of possible states.

Constraints:

1 <= [Link] <= 500


string[i] is either '+' or '-'
Sample Input-1:
---------------
--++-

Sample Output-1:
----------------
[-----]

Explanation:
-------------
++ will be converted as --. Then game ends.
Sample Input-2:
---------------
--+++-++

Sample Output-2:
----------------
[----+-++, --+---++, --+++---]

*/

import [Link].*;
class Test {
public List<String> generatePossibleNextMoves(String s) {
List<String> list = new ArrayList<String>();
for (int i = 1; i < [Link](); i++) {
if ([Link](i) == '+' && [Link](i - 1) == '+') {
[Link]([Link](0, i - 1) + "--" + [Link](i + 1, [Link]()));
}
}
return list;
}

public static void main(String args[])


{
Scanner sc=new Scanner([Link]);
String str=[Link]();

[Link](new Test().generatePossibleNextMoves(str));
}
}

/*
Motu Patlu are good friends, Motu loves to eat Samosas,
He is given N Boxes of samosas[], box-'a' has samosas[a].
He can choose two boxes having highest number of samosas each time,
box-i and box-j, where samosas[i] <= samosas[j].
If samosas[i] == samosas[j] , then eat all the samosas from both boxes;
If samosas[i] != samosas[j] , then eat all samosas from box-i,
and from box-j eat only samosas[i] samosas, and left with ( samosas[j]-samosas[i] )
If the box becomes empty, remove the box.

At the end, there is at most 1 box left. Return the number of samosas left
in that box (or 0 if there are no boxes left.)

Input Format:
-------------
N space separated integers, number of samosas[i] in box[i]

Output Format:
--------------
Print number of the samosas left at the end.

Sample Input-1:
---------------
274181

Sample Output-1:
----------------
1

Explanation:
------------
Boxes are numbered from 0,1,2,...,N-1.

Motu selects, box-1 has 7 samosas and box-4 has 8 samosas eat 14 samosas, boxes becomes
[2,4,1,1,1]
Motu selects, box-0 has 2 samosas and box-1 has 4 samosas eat 4 samosas, boxes becomes [2,1,1,1]
Motu selects, box-1 has 1 samosa and box-0 has 2 samosas eat 2 samosas, boxes becomes [1,1,1]
Motu selects, box-0 has 1 samosa and box-1 has 1 samosa eat 2 samosas, boxes becomes [1]
Finally left with 1 box, box contains 1 samosa in it.

=== testcases ===


case =1
input =2 7 4 1 8 1
output =1

case =2
input =18 4 12 4 16 4 16 9 7 11
output =1

case =3
input =11 6 33 36 30 39 35 4 33 8 6 35 42 26 40
output =2
case =4
input =11 12 20 21 65 6 7 8 9 10
output =3

case =5
input =69 84 60 80 78 82 74 78 74 70 73 77 68 83 69 63 64 61 82
output =47

case =6
input =81 54 40 69 77 42 81 74 44 40 71 50 68 78 58 59 73 85 84
output =14

case =7
input =55 70 55 82 63 83 55 62 45 84 67 45 79 67 43 60 51 63 59 77 68 65 61 48 78
output =25

case =8
input =68 51 59 71 73 66 58 74 50 51 64 64 63 71 70 67 51 60 66 70 56 53 62 62 56
output =42

*/

import [Link];
import [Link];
import [Link];
import [Link].*;

class Test {
public static int lastBox(int[] A)
{
PriorityQueue<Integer> pq =
new PriorityQueue<>([Link]());

for (int a : A) //2 7 4 1 8 1


[Link](a);

while ([Link]() > 1)


[Link]([Link]() - [Link]());

return [Link]();
}

public static void main(String args[] ) throws IOException {

Scanner sc=new Scanner([Link]);


int n=[Link]();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=[Link]();
[Link](lastBox(arr));
}
}

/*
Given the array of integers nums, you will choose two different indices i and j of that array.

Return the maximum value of (nums[i]-1)*(nums[j]-1).

input =4
3452
output =12
If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is,
(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.

input =4
1545
output =16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-
1)*(5-1) = 16.

input =2
37
output =12
*/
import [Link].*;
class maxTwoProduct_pq
{
public static int maxProduct(int[] nums) {
PriorityQueue<Integer> pq=new PriorityQueue<Integer>([Link]());

for (int a : nums)


[Link](a); // 3 4 5 2 ==> 5 4 3 2

return ([Link]()-1) * ([Link]()-1);


}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
int n=[Link]();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=[Link]();
[Link](maxProduct(arr));
}
}

/*
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is
valid.

An input string is valid if:


Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Example 1:
input =()
output =true

input =()[]{}
output =true

input (]
output =false
*/
class valid_paranthesis
{
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : [Link]()) {
if (c == '(')
[Link](')');
else if (c == '{')
[Link]('}');
else if (c == '[')
[Link](']');
else if ([Link]() || [Link]() != c)
return false;
}
return [Link]();
}
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
/*
case =1
input =(((((())))))
output =true

case =2
input =()()()()
output =true
case =3
input =(((((((()
output =false

case =4
input =((()(())))
output =true

case =5
input =()[]{}
output =true

case =6
input =(]
output =false
*/

/*
write a java program to read sentences and return the maximum number of words that appear in a
single sentence.

example:
input =alice and bob love leetcode,i think so too,this is great thanks very much
outupt =6

input =i love coding,ramu is good boy,a b c d e


output =5

input =keshav memorial college of engineering,keshav memoraial institute of technology,neil gogte


institute of technology hyd
output =6
*/
import [Link].*;
class Maximum_Number_of_words_found_inSentences
{
public static int mostWordsFound(String[] sentences) {
int maxLen = 0;

for (String currSent : sentences) {


int currLen = [Link](" ").length;
if (maxLen < currLen)
maxLen = currLen;
}
return maxLen;
}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
String[] line=[Link]().split(",");
[Link]( mostWordsFound(line));
}
}

/*
Given an array of strings words and a string s, determine if s is an acronym of words.

The string s is considered an acronym of words if it can be formed by concatenating the first
character of each string in words in order.

For example, "ab" can be formed from ["apple", "banana"], but it can't be formed from ["bear",
"aardvark"].

Return true if s is an acronym of words, and false otherwise.

input =alice bob charlie


abc
output =true
Explanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c',
respectively. Hence, s = "abc" is the acronym.

input =an apple


a
output =false
Explanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively.
The acronym formed by concatenating these characters is "aa".
Hence, s = "a" is not the acronym.

input =never gonna give up on you


ngguoy
output =true
Explanation: By concatenating the first character of the words in the array, we get the string
"ngguoy".
Hence, s = "ngguoy" is the acronym.

*/
import [Link].*;
class Acronym_Words
{
public static boolean isAcronym(List<String> words, String s) {
if ([Link]()!=[Link]())
return false;

for (int i=0;i<[Link]();i++)


if ([Link](i)!=[Link](i).charAt(0))
return false;

return true;
}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
String line=[Link]();
String[] words=[Link](" ");
List<String> list=new ArrayList<String>();
list=[Link](words);

String s=[Link]();
[Link](isAcronym(list,s));
}
}

/*Rahul and Rohith are playing a switch game.

Rahul has given a string PresentState that contains only '+' and '-' . Both take turns to switch two
consecutive "++" into "--" .

The game ends when a person can no longer make a move, and therefore the other person will be
the winner.

Return all possible states of the string presentState after one valid move.
You may return the answer in any [Link] there is no valid move, return an empty list [] .

input =--++-
output =[-----]

Explanation:
++ will be converted as --. Then game ends.

input =--+++-++
output =[----+-++, --+---++, --+++---]

*/

import [Link].*;
class Test {
public List<String> generatePossibleNextMoves(String s) {
List<String> list = new ArrayList<String>();
for (int i = 1; i < [Link](); i++)
{
if ([Link](i) == '+' && [Link](i - 1) == '+')
{
[Link]([Link](0, i - 1) + "--" + [Link](i + 1, [Link]()));
}
}
return list;
}

public static void main(String args[])


{
Scanner sc=new Scanner([Link]);
String str=[Link]();

[Link](new Test().generatePossibleNextMoves(str));
}
}

You might also like