Check if a string is rotation of another WITHOUT concatenating

后端 未结 11 1417
死守一世寂寞
死守一世寂寞 2020-12-25 08:11

There are 2 strings , how can we check if one is a rotated version of another ?

For Example : hello --- lohel

One simple solution is by co

11条回答
  •  无人及你
    2020-12-25 08:55

        String source = "avaraavar";
        String dest =   "ravaraava";
    
        System.out.println();
        if(source.length()!=dest.length())
            try {
                throw (new IOException());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        int i = 0;
        int j = 0;
        int totalcount=0;
        while(true)
        {
            i=i%source.length();    
            if(source.charAt(i)==dest.charAt(j))
            {   
                System.out.println("i="+i+" , j = "+j);
                System.out.println(source.charAt(i)+"=="+dest.charAt(j));
                i++;
                j++;
                totalcount++;   
            }
            else
            {
                System.out.println("i="+i+" , j = "+j);
                System.out.println(source.charAt(i)+"!="+dest.charAt(j));
                i++;
                totalcount++;   
                j=0;
            }
            if(j==source.length())
            {
                System.out.println("Yes its a rotation");
                break;
            }
            if(totalcount >(2*source.length())-1)
            {
                System.out.println("No its a rotation");
                break;
            }
        }
    

提交回复
热议问题