Array, linked list, string rotation (not finished)

Source: Internet
Author: User

string Manipulation topic One: Rotation of the string (left-hand operation)Given a string, it is required to move several characters in front of the string to the end of the string, such as the string "ABCdef" before the 2 characters ' a ' and ' B ' moved to the end of the string, so that the original string into the string "Cdefab". Write a function that requires an O (n) time complexity for a string operation of length n and an O (1) space complexity. Topic Source: Programmer Programming Art: Interview and Algorithmic experience Microsoft interview 100 26th Sword Point of Offer 42nd, flip string vs left rotation string analysis: Solution One: Violence Law ———— cyclic shift, time complex The impurity is O (m*n), does not meet the requirements of the solution 2:3-step inversion method for an array of TS, to achieve the rotation of the array, the respective words set to rotate, and then rotate the entire array, you can get the St code: C + + implementation
#include <iostream> #include <string.h>using namespace std;void  reverse (char *str,int start,int end) { While     (start<end)   //an article with start! =end as a condition of judgment, this is not possible, because when the number of characters is even, the                         //start pointer and the end pointer are interleaved. Will not meet     {       char  temp = Str[start];         Str[start] = Str[end];         Str[end] = temp;         start++;         end--;}    } void Rotatestr (char * str,int k) {     if (str==null| | strlen (str) ==0| | k<=0) return; int len = strlen (str);      K = K%len;           If K==len, does not rotate, but actually rotates the string two times      reverse (str,0,k-1);  First to rotate the first k elements      reverse (str,k,len-1);      Reverse (str,0,len-1);}

  

Consider the boundary problem: 1. When the string is null, the value of 2.K is negative or 3. K = K%len is used here when the number is greater than or equal to the string length. Java ImplementationString strings in Java are constants, immutable, but StringBuffer are mutable, and have reverse () methods; because strings are constants, they cannot be changed after they are created, so there is no algorithm for the Space O (1)
1  Public classReversekstr2 {3       Publicstring Reversekelement (string str,k)4      {5           if(str==NULL|| Str.length () ==0| | k<=0)return NULL;6            intLen =str.length ();7k= k%Len;8StringBuffer SB1 =NewStringBuffer (str.substring (0, k));9StringBuffer SB2 =NewStringBuffer (str.substring (K,len));Ten sb1.reverse (); One sb2.reverse (); A sb1.append (SB2); -           returnsb1.reverse (). toString (); -      } the}

Title Two: rotation of the string (right-handed operation)Title: Write a program, in the original string to move the end of the string m characters to the head of the string, requires: the length of the string is N time complexity O (n), the space Complexity of O (1). For example, the original string is "Ilovebaofeng", m=7, and the output is: "Baofengilove". still three-paragraph law, the first paragraph 0,len-m-1, the second paragraph Len-m,lenBoundary condition: m>=len,m<=0, when return does not execute topic Three: The rotation of sentences Topics :The word flips. Enter an English sentence, flipping the order of the words in the sentence, but the order of the characters in the word is constant, and the words in the sentence are separated by spaces. For simplicity, punctuation is treated like ordinary letters. For example, enter "I am a student.", then output "student." A am I ". L description of the topic in Eetcode: Given An input string, reverse the string word by word. For example, Given s = "The Sky is Blue" and return "Blue is Sky the". Click to show Clarification. Clarification:
    • What constitutes a word?
      A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces?
      Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between and words?
      Reduce them to a single space in the reversed string.
Analysis: 1. Spaces separate words 2. Note that there are no first and last characters in the returned string 3. If there are multiple spaces between two words, just leave a space after returning Answer:Java implementation, it is easy to think of Java implementation, the string word breaker (Split function) into a string array, inverted into stringbuffer.
1  Public classSolution {2      Publicstring Reversewords (string s) {3         if(s==NULL)returns;4 S.trim ();5string[] Strarray = S.split ("");6         intLen =strarray.length;7StringBuilder SB =NewStringBuilder ();8              for(inti=len-1;i>=0;i--)9             {Ten                if(Strarray[i].length () >0)//Prevent accidental addition of spaces One                { A sb.append (Strarray[i]); -Sb.append (""); -                } the             } -                returnsb.tostring (). Trim (); -     } -}

However, in the interview process, the examiner would like to have the bottom of the implementation of C + + implementation
1 classSolution {2  Public:3     voidReversewords (String &s) {4 string str;5        intI =s.length ()-1;6        while(i>=0)7       { 8            while(i>=0&&s[i]== ")9i--;Ten        One           if(i<0) Break;//If there are no non-whitespace elements, jump out of the A           if(Str.length ()!=0) str.append ("");//If, already have a word, then add a space, the preceding sentence, guarantee, and the words added in the back; -        - string temp; the            while(i>=0&&s[i]!= ") - {temp.push_back (s[i]); -i--; -          } + Reverse (Temp.begin (), Temp.end ()); - str.append (temp); +       } As=str;  at     }     -};

rotation of integers: Reverse Integer Total accepted:37856 total submissions:94980 My submissions Question Solution Reverse digits of an integ Er. EXAMPLE1:X = 123, return 321example2:x = -123, return-321 Click to show spoilers. Has a thought about this? Here is some good questions to ask before coding. Bonus points for if you have already thought through this! If the last digit are 0, what should the output being? ie, cases such as 10, 100. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer and then the reverse of 1000000003 overflows. How should handle such cases? Throw an exception? Good, but what if throwing an exception was not an option? You would then has to re-design the function (ie, add an extra parameter). Note: 1.100,10 The result of such a number, 2. Whether to consider overflow
1  Public classSolution {2      Public intReverseintx) {3         BooleanFlag =true;4         if(x<0)  5         { 6flag=false;7x = -1*x;8         }9        intNewint = x%10;Ten        intTemp=x/10; One          while(temp!=0) A          { -            if(flag&&newint>=214748364&&temp%10>=7)returnInteger.max_value; -            if(!flag&&newint>=214748364&&temp%10>=8)returnInteger.min_value; theNewint= newint*10+temp%10; -Temp=temp/10; -           } -          if(flag) +             returnNewint; -           Else  +             return-1*Newint;  A     } at}

Array, linked list, string rotation (not finished)

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.