Array and string (arrays and strings)

Source: Internet
Author: User
Tags stub stringbuffer

1. Implement an algorithm that determines whether all the characters of a string are all different. What if you don't allow the use of additional data structures?

 Public classUniquechars { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string = "ABCDEFGFEDCBA";                System.out.print (Isuniquechars (string)); }     Public Static Booleanisuniquechars (String str) {if(Str.length () > 256) {            return false; }        Boolean[] Char_set =New Boolean[256];  for(inti = 0; I < str.length (); i++) {            intval =Str.charat (i); if(Char_set[val]) {return false; } Char_set[val]=true; }        return true; }}
View Code

Note: Confirm to the interviewer whether the above string is an ASCII string or a Unicode string. If it is not an ASCII string, the storage space needs to be expanded, but the remaining logic is unchanged.

This is assumed to be an ASCII string. First do an optimization, if the string length is greater than the number of characters in the alphabet, it will return false directly. After all, if the alphabet is only 256 characters, there can be no more than 280 characters in the string.

A Boolean array is then constructed, and the tag of the index value I indicates whether the string contains an I character in the alphabet. If the character appears for the second time, it returns false immediately. Time complexity O (n), Spatial complexity O (1).

If you are not allowed to use additional data structures:

(1) compares each character in a string with its remaining characters. Time complexity is O (N2), Space complexity O (1).

 Public classUniquechars { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string = "ABCDEFGFEDCBA";                System.out.print (Isuniquechars (string)); }        Public Static Booleanisuniquechars (String str) {if(Str.length () > 256) {            return false; }         for(inti = 0; I < str.length (); i++) {             for(intj = i + 1; J < Str.length (); J + +) {                if(Str.charat (i) = = Str.charat (j))return false; }        }        return true; }}
View Code

(2) If the input string is allowed to be modified, the string can be sorted in O (Nlogn), and then the linear check is that there are no adjacent characters in exactly the same situation.

2. Implement the Void reverse (char* str) function in Java, which reverses a null-terminated string.

 Packagearrayandstring; Public classReverse { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string = "ABCDEFG";    System.out.println (ReverseString2 (string)); }    //The simplest way     Public Staticstring reversestring (String inistring) {//Write code hereStringBuffer tmp =NewStringBuffer (inistring); TMP=Tmp.reverse (); returntmp.tostring (); }    //The most common method     Public Staticstring ReverseString2 (String inistring) {Char[] Array =Inistring.tochararray (); String Reverse= "";//Note that this is an empty string, NOT null          for(inti = array.length-1; I >= 0; i--) {Reverse+=Array[i]; }         returnreverse; } }
View Code

3. Given two strings, write a program that determines whether the character of one of the strings is rearranged to become another string.

Solution One: The string is sorted after comparison, if they have the same order of characters, that is, each other as a modified word.

ImportJava.util.*; Public classIsanagram { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string1 = "Aceg"; String string2= "Cega";        System.out.println (permutation (string1, string2)); }         Public Staticstring Sort (string s) {Char[] content =S.tochararray ();        Arrays.sort (content); return NewString (content); }         Public Static Booleanpermutation (string s, String t) {if(S.length ()! =t.length ()) {            return false; }        returnsort (s). Equals (sort (t)); }}
View Code

Solution Two: Use the definition of the modified word--the same number of characters that make up two words, traverse the alphabet, count the occurrences of each character, and then compare the two arrays.

 Public classIsanagram { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString string1 = "Aceg"; String string2= "Cega";        System.out.println (permutation (string1, string2)); }     Public Static Booleanpermutation (string s, String t) {if(S.length ()! =t.length ()) {            return false; }                int[] Letters =New int[256]; Char[] S_array =S.tochararray ();  for(CharC:s_array) {Letters[c]++; }         for(inti = 0; I < t.length (); i++) {            intc = (int) T.charat (i); if(--letters[c] < 0) {                return false; }        }        return true; }}
View Code

Note: Check with the interviewer to see if the inflection is case sensitive and whether to consider whitespace characters.

It is assumed that the conjugation is case-sensitive, and that whitespace is taken into account as an ASCII string. First do an optimization, compare the length of two strings, as long as the length of the different can not be a modified word.

4. Write a method that replaces all spaces in the string with "%20". It is assumed that there is enough space at the end of the string to hold new characters and to know the "true" length of the string. (Note: If implemented in Java, use a character array implementation to manipulate directly on the array.) )

Idea: Perform two scans. The first scan counts the number of spaces in the string to figure out how long the final string will be. The second scan really starts to reverse-edit the string, detects that a space will copy the%20 to the next location, or, if not blank, copies the original character.

Note: When dealing with string manipulation problems, it is common practice to start editing from the end of the string, and then reverse the operation from backward to forward. Because there is an extra buffer at the end of the string, you can modify it directly without worrying about copying the original data.

Array and string (arrays and strings)

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.