Ans

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

public static void main(String[] args) {

String[] operations={"5","2","C","D","+"};
int sum=0;
int[] arr = new int[operations.length];
int count=0;

for(int i=0;i<operations.length;i++){
// System.out.println(count + " " + operations[i]);
if(operations[i].equals("C")){
arr[--count]=0;
}
else if(operations[i].equals("D")){
arr[count] = 2 * arr[count-1];
count++;
}
else if(operations[i].equals("+")){
arr[count]= arr[count-1] + arr[count-2];
count++;
}
else{
// System.out.println(operations[i]);
arr[count] = Integer.parseInt(operations[i]);
count++;
}
}
for(int j=0;j<arr.length;j++){
//System.out.println(arr[j]);
sum += arr[j];
}
System.out.println(sum);
}
***************************************************************************
def calPoints(self, operations: list[str]) -> int:
stack = []
operations=["5","2","C","D","+"]
for i in range(len(operations)):
if operations[i]=="D":
stack.append(stack[-1]*2)
elif operations[i]=="C":
stack.pop(-1)
elif operations[i]=="+":
stack.append(stack[-1]+stack[-2])
else:
stack.append(int(operations[i]))
print(sum(stack))
return sum(stack)
*****************************************************************
public List<Integer> findSubstring(String s, String[] words) {
// Resultant list
List<Integer> indices = new ArrayList<>();
// Base conditions
if (s == null || s.isEmpty() || words == null || words.length == 0) {
return indices;
}
// Store the words and their counts in a hash map
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
// Length of each word in the words array`
int wordLength = words[0].length();
// Length of all the words combined in the array
int wordArrayLength = wordLength * words.length;
// Loop for the entire string
for (int i = 0; i <= s.length() - wordArrayLength; i++) {
// Get the substring of length equal to wordArrayLength
String current = s.substring(i, i + wordArrayLength);
// Map to store each word of the substring
Map<String, Integer> wordMap = new HashMap<>();
// Index to loop through the words array
int index = 0;
// Index to get each word in the current
int j = 0;
// Loop through each word of the words array
while (index < words.length) {
// Divide the current string into strings of length of
// each word in the array
String part = current.substring(j, j + wordLength);
// Put this string into the wordMap
wordMap.put(part, wordMap.getOrDefault(part, 0) + 1);
// Update j and index
j += wordLength;
index++;
}
// At this point compare the maps
if (wordCount.equals(wordMap)) {
indices.add(i);
}
}
return indices;

You might also like