Interview question set-array and string

Source: Internet
Author: User

Hash table

While not all problems can be solved with hash tables, a shocking number of interview problems can be before your interview, make sure to practice both using and implementinghash tables

Although the hash table cannot solve all the problems, most problems in the interview can be solved with it. Before the interview, be sure to prepare the use and implementation of the hash table.

1 Public hashmap buildmap (student [] Students) {2 hashmap map = new hashmap (); 3 for (student s: Students) map. put (S. GETID (), S); 4 return map; 5}

Arraylist (dynamically resizing array ):

Array linked list

An arraylist, or a dynamically resizing array, is an array that resizes itself as needed whilestill providing O (1) access a typical implementation is that when a vector is full, the arraydoubles in size each doubling takes O (n) time, but happens so rarely that its amortized timeis still O (1)

Multiple linked lists (arrays with dynamically changing sizes) can expand the array capacity as needed and provide random access efficiency of O (1. A typical implementation of an array linked list is to double the array capacity when the upper limit of the array is reached. Although the time complexity during capacity expansion is O (n), this rarely happens, so the total time overhead can be approximately O (1 ).

1 Public arraylist Merge (string [] words, string [] More) {2 arraylist sentence = new arraylist (); 3 for (string W: words) sentence. add (w); 4 for (string W: More) sentence. add (w); 5 return sentence; 6}

Stringbuffer/stringbuilder

String

Question: What is the running time of this code?
1 Public String makesentence (string [] words) {2 stringbuffer sentence =
New stringbuffer (); 3 for (string W: words) sentence. append (w); 4 return
Sentence. tostring (); 5}

Q: What is the time complexity of the following code?

Answer:
O (N ^ 2), where N is the number of letters in sentence here's why: each
Time youappend a string to sentence, you create a copy of sentence and
Run through all the letters insentence to copy them over if you have
Iterate through up to n characters each time in the loop, and you're
Looping at least N times, that gives you an O (N ^ 2) Run Time ouch! With
Stringbuffer (or stringbuilder) can help you avoid this problem 1 Public
String makesentence (string [] words) {2 stringbuffer sentence = new
Stringbuffer (); 3 for (string W: words) sentence. append (w); 4 return
Sentence. tostring (); 5}

A: O (N ^ 2 ),
Here, n is the number of characters in the string sentence. The reason is as follows: each time you append an array to the string sentence string, you need to copy it again.
The characters in sentence. Each copy needs to traverse sentence from start to end. In this way, the time complexity of appending all words to sentence is
O (N ^ 2 ).

1.1
Implement an algorithm to determine if a string has all unique
Characters what if you can not use additional data structures?
For
Simplicity, assume char set is ASCII (if not, we need to increase
Storage size the rest of the logic wocould be the same) Note: This is
Great thing to point out to your interviewer!
1 public static Boolean isuniquechars2 (string Str ){
2 Boolean [] char_set = new Boolean [0, 256];
3 For (INT I = 0; I <Str. Length (); I ++ ){
4 int val = Str. charat (I );
5 If (char_set [Val]) return false;
6 char_set [Val] = true;
7}
8 return true;
9}
We can reduce our space usage a little bit by using a bit vector we
Will assume, in the below code, that the string is only lower case 'A'
Through 'Z' this will allow us to use just a single int
Alternatively, we cocould do the following:

1 check every char of the string with every other char of the string
For duplicate occurrences this will take O (N ^ 2) time and no space
2
If we are allowed to destroy the input string, We cocould sort the string
In O (n log n) time and then linearly check the string for neighboring
Characters that are identical careful, though-Sort sorting algorithms
Take up extra space

1.1 design an algorithm to determine whether all characters in a string are unique. What if no additional data structure is available?
Solution 1.1: assume that all characters in the string are ASCII codes (if not, the storage space can be increased, and the algorithm logic is the same ). "Hypothesis" is very important in your interview.

The time space complexity of the algorithm is O (n), and N is the length of the string.

Using bit sequence instead of array can further save space. Here we need to assume that the character in the string is 'A'-'Z '. In this way, a variable of the int type can be used to record whether a character appears.

There are other solutions to this question:
1. Check the number of occurrences of each character in the string. the time complexity of this method is O (n ^ 2), but the space complexity is 0.
2. If the content in the string can be damaged. We can sort the characters in the string (the time complexity is O (nlogn), and traverse a character in the string when the adjacent characters are the same. However, note that some sorting algorithms require additional storage space.

1.2
Write code to reverse a C-style string (c-string means that "ABCD" is
Represented as five characters, including the null character) Solution
: This is a classic interview question the only "gotcha" is to try to do
It in place, and to be care-ful for the NULL Character 1 void
Reverse (char * Str) {2 char * end = STR; 3 char TMP;
4 If (STR) {5 while (* End ){
6 + + end; 7} 8 -- end;
9 While (STR <End) {10 TMP =
* STR; 11 * STR ++ = * end; 12 * end -- =
TMP; 13} 14} 15}

1.2 C-language string inversion algorithm
(C string: for example, the "ABCD" string contains five characters. The last character is/0, indicating that the string ends .)
Answer: 1.2:
This is a frequently asked question for interviews. If you know, you can start writing code immediately.

1.3
Design an algorithm and write code to remove the duplicate characters
In a string without using any additional buffer Note: one or two
Additional variables are fine an extra copy of the array is notfollow
Upwrite the test cases for this method

1.3 design an algorithm to remove duplicate characters from the string without any additional buffering. And design test cases for your algorithms. NOTE: If one or two variables are used as OK, copying the entire array won't work.
Answer: 1.3:
No string buffer algorithm
1. Determine whether each character is a repeated character.
2. Duplicate characters are skipped directly. Non-duplicate characters are recorded.
The time complexity is O (n ^ 2)

Test cases:
1. No repeated characters: ABCD;
2. All repeated characters: AAAA;
3. invalid string: NULL;
4. Repeated strings: aaaabbbb;
5. non-consecutive repeated strings: abcabc;

String Buffer Algorithm:

1. No repeated characters: ABCD;
2. All repeated characters: AAAA;
3. invalid string: NULL;
4. Empty string: empty
5. Repeated strings: aaaabbbb;
6. non-consecutive repeated strings: abcabc;

1.4 write a method to decide if two strings are anagrams or not

1.4 write a function to determine whether two strings contain the same characters.
Answer: 1.4:
There are two solutions to this question
Method 1 sorting

Method 2 counting

1.5 write a method to replace all spaces in a string with '% 20'

1.5 write code to replace the space in the string with '% 20'
Answer: 1.5:
Algorithm flow:
1. traverse the string and record the number of spaces;
2 re-Parse from the end of the string:
(1) If the current character is a space, write the string '% 20'
(2) A record is recorded directly without spaces.

1.6
Given an image represented by an nxn matrix, where each pixel in
Image is 4 bytes, write a method to rotate the image by 90 degrees can
You do this in place?

1.6 shows an image, which is expressed as nxn. Each pixel is 4 bytes. Write a function to rotate the image 90 °.
Answer: 1.6:
The image rotation can divide the pixels into one circle, and then rotate from the outermost layer. When an element in a certain circle is rotated, it is equivalent to switching the corresponding top, bottom, left, and right.

1.7 write an algorithm such that if an element in an mxn matrix is 0, its entire row and column is set to 0

1.7 implementation algorithm: In an mxn matrix, if an element is 0, the row and column are set to zero.
Answer: 1.7:
First, let's look at the question. First, traverse the Matrix. If there is 0 element, the row and column will be set to zero. However, when this method is executed, the entire matrix is changed to 0.
A work und is to record whether there is zero in the matrix of another mxn, and then set the corresponding columns to zero Based on the record. However, the space complexity of this method is O (mxn ). Is there any room for improvement?
After observation, we only need to record which column and which line need to be set to zero. The new record method is to use two arrays rows [] and Col [] to record the rows and columns that need to be set to zero. The algorithm code for this method is as follows:

1.8
Assume you have a method issubstring which checks if one word is
Substring of another given two strings, S1 and S2, write code to check
If S2 is a rotation of S1 using only one call to issubstring (I e,
"Waterbottle" is a rotation of "erbottlewat ")

1.8 assume that you already have a function for issubstring (S1, S2) to determine whether string S1 is a substring of string S2. Now, we will give you a string S1 and S2, so that you can determine whether S1 is obtained by S2 Cyclic Displacement. You can only call issubstring once in your algorithm (for example, you can get "erbottlewat" by "waterbottle ").
Answer: 1.8:
Algorithm Description:
1 If length (S1 )! = Length (S2) returns false
2 is the connection between S1 and itself, get the new string s1', and call issubstring (S2, s1') to determine whether S2 is s1.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.