zoukankan      html  css  js  c++  java
  • 字符串按word反转

    方法一、不用栈

    void reverseChar(char* str, int len)
    {
    	char* q = str+len-1;
    	char* p = str;
    
    	if (!len)
    		return;
    
    	while( p<q )
    	{
    		char tmp = *p;
    		*p = *q;
    		*q = tmp;
    		p++;
    		q--;
    	}
    
    	for (int i=0; i<len; i++)
    		cout << str[i];
    	cout << endl;
    }
    
    void reverseWord(char* str)
    {
    	char* p = str;
    	int count = 0;
    	int total = 0;
    
    	while(1)
    	{
    		p++;
    		count++;
    		total++;
    
    		if ( *p==' ' || *p=='\0' )
    		{
    			reverseChar(p-count, count);
    			//note that, it is -1,not 0
    			count=-1;
    			
    			if ( *p=='\0' )
    			{
    				break;
    			}
    		}
    	}
    
    	reverseChar(str, total);
    }
    

      

    方法二、采用了两个stack,一个用于整个字符串的反转,一个用于保证word内部顺序不变。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    char* reverse_word(char* str)
    {
        stack<char> st;
        stack<char> word;
      
        char* p = str;
      
        st.push('\0');
        while( *p != '\0')
        {
            while( *p == ' ')
                st.push(*p++);
      
            if ( *p == '\0')
                break;
      
            while( *p != '\0' && *p != ' ')
                word.push(*p++);
      
            while( !word.empty() )
            {
                st.push( word.top() );
                word.pop();
            }
        }
      
        p = str;
        while( *p != '\0' )
        {
            *p = st.top();
            st.pop();
            p++;
        }
      
        return str;
    }

     

  • 相关阅读:
    布局重用 include merge ViewStub
    AS 常用插件 MD
    AS 2.0新功能 Instant Run
    AS .ignore插件 忽略文件
    AS Gradle构建工具与Android plugin插件【大全】
    如何开通www国际域名个人网站
    倒计时实现方案总结 Timer Handler
    AS 进行单元测试
    RxJava 设计理念 观察者模式 Observable lambdas MD
    retrofit okhttp RxJava bk Gson Lambda 综合示例【配置】
  • 原文地址:https://www.cnblogs.com/simonote/p/3095260.html
Copyright © 2011-2022 走看看